Sort Strings in Lexicographical Order in C

Here we will write a program to sort elements in lexicographical order in C language (dictionary order). For this purpose we will use strcmp() and strcpy(), which are function defined under <string.h>. The strcmp() function used to compare two strings and strcpy() used to copy the string. Prerequisites:- 2d array of strings in C

Lexicographic order is the way of ordering words based on the alphabetical order of their component letters. It is also known as lexical order, dictionary order, and alphabetical order. It is similar to the way we search for any word in the dictionary. We start our search by simply searching for the first letter of the word. Then we try to find the second letter and so on. The words in the dictionary are arranged in lexicographic order.

#include<stdio.h>
#include<string.h>
int main()
{
   char str[10][50],temp[50];
   int i,j;

   printf("Enter 10 Words:\n");

   for(i=0;i<10;i++)
   scanf("%s[^\n]",str[i]);

   for(i=0;i<9;i++)
   {
     for(j=i+1;j<10;j++)
     {
       if(strcmp(str[i],str[j])>0)
       {
         strcpy(temp,str[i]); 
         strcpy(str[i],str[j]);
         strcpy(str[j],temp);
       }
     }
   }
   printf("\nIn lexicographical order: \n");

   for(i=0;i<10;i++)
   puts(str[i]);

   return 0;
}

Output:-

Enter 10 String:
JavaScript
Python
Java
C/CPP
PHP
Swift
C#
Ruby
Objective-C
SQL

In lexicographical order:
C#
C/CPP
Java
JavaScript
Objective-C
PHP
Python
Ruby
SQL
Swift

The program lexicographical order in C language used to arrange a list of strings. The lexicographical order is also called dictionary order. In the above program, strings are taken from the user. To store all these strings we use a two-dimensional array of strings. Now, each character of the string is compared with all other strings using strcmp() function. The function returns a positive value when the second string is smaller than the first string. In this case, the second string is replaced or swap with the first string. To swap these strings we use strcpy() function and one another string temp. Finally, we get the result.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

More C programming Examples on String

Leave a Reply