C Program to Sort Elements in Lexicographical Order (Dictionary Order)

C Program to Sort Elements in Lexicographical Order (Dictionary Order)

In this example, you will learn to sort 5 strings entered by the user in the lexicographical order (dictionary order).

To understand this example, you should have the knowledge of the following C programming topics:


Sort strings in the dictionary order

#include <stdio.h>
#include <string.h>

int main() {
   char str[5][50], temp[50];
   printf("Enter 5 words: ");

   // Getting strings input
   for (int i = 0; i < 5; ++i) {
      fgets(str[i], sizeof(str[i]), stdin);
   }

   // storing strings in the lexicographical order
   for (int i = 0; i < 5; ++i) {
      for (int j = i + 1; j < 5; ++j) {

         // swapping strings if they are not in the lexicographical order
         if (strcmp(str[i], str[j]) > 0) {
            strcpy(temp, str[i]);
            strcpy(str[i], str[j]);
            strcpy(str[j], temp);
         }
      }
   }

   printf("\nIn the lexicographical order: \n");
   for (int i = 0; i < 5; ++i) {
      fputs(str[i], stdout);
   }
   return 0;
}

Output

Enter 5 words: R programming
JavaScript
Java
C programming
C++ programming

In the lexicographical order:
C programming
C++ programming
Java
JavaScript
R programming

To solve this program, a two-dimensional string named str is created. The string can hold a maximum of 5 strings and each string can have a maximum of 50 characters (including the null character).

In the program, we have used two library functions:

These functions are used to compare strings and sort them in the correct order.