Home » Sort Strings in Lexicographical Order in C

Sort Strings in Lexicographical Order in C

Learn about Sort Strings in Lexicographical Order in C in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

Contents

C program to Sort Strings in Lexicographical Order

Lexicographic order refers to the method of organizing words based on the alphabetical order of their constituent letters. It’s also referred to as lexical order, dictionary order, and alphabetical order. It’s comparable to how we look up words in the dictionary. We begin our search by looking for the first letter of the word. Then we look for the second letter, and so on. The terms in the dictionary are listed in alphabetical order.

In this section, we will create a C program to sort elements in lexicographical order (dictionary order). We shall use strcmp() and strcpy(), which are functions specified in <string.h>, for this purpose. The strcmp() method compares two strings, and strcpy() copies the string.

#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 Words:
Python
C
Javascript
PHP
HTML
Ruby
Rails
Cloud
Swift
Java

In lexicographical order:
C
Cloud
HTML
Java
Javascript
PHP
Python
Rails
Ruby
Swift

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
C Program to Search a String in the List of Strings
Copy Input to Output Using C Programming