C Program to Sort the list of Strings
C Program for sorting the list of names
Write a C program which will accept multiple strings fron the user and will sort them in ascending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char *str[5], *temp; int i, j, n; printf("\nHow many names do you want to have?"); scanf("%d", &n); for (i = 0; i < n; i++) { printf("\nEnter the name %d: ", i); flushall(); gets(str[i]); } for (i = 0; i < n; i++) { for (j = 0; j < n - 1; j++) { if (strcmp(str[j], str[j + 1]) > 0) { strcpy(temp, str[j]); strcpy(str[j], str[j + 1]); strcpy(str[j + 1], temp); } } } flushall(); printf("\nSorted List : "); for (i = 0; i < n; i++) puts(str[i]); return (0); } |
Output :
1 2 3 4 5 6 7 | How many names do you want to have? 4 Enter the name 0: pri Enter the name 1: prt Enter the name 2: prq Enter the name 3: pra Sorted List : pra pri prq prt |
Explanation :
We are checking each successive strings using strcmp() function.
1 2 3 4 5 | if(strcmp(str[j],str[j+1])>0) { strcpy(temp,str[j]); strcpy(str[j],str[j+1]); strcpy(str[j+1],temp); } |
If string is greater than the successive string then we are swapping the strings.