Google News
logo
C Program to Sort Elements in Lexicographical Order (Dictionary Order)
In the following example of sorting elements in lexicographical order (dictionary order) implemented in C :
Program :
#include <stdio.h>
#include <string.h>

int main() {
    char words[][50] = {"dog", "cat", "apple", "banana", "zebra", "horse"};
    int i, j, n;
    char temp[50];

    n = sizeof(words)/sizeof(words[0]);

    printf("Unsorted words: \n");
    for (i = 0; i < n; i++)
        printf("%s\n", words[i]);

    // Sorting the words in lexicographical order
    for (i = 0; i < n-1; i++) {
        for (j = i+1; j < n; j++) {
            if (strcmp(words[i], words[j]) > 0) {
                strcpy(temp, words[i]);
                strcpy(words[i], words[j]);
                strcpy(words[j], temp);
            }
        }
    }

    printf("\nSorted words in lexicographical order: \n");
    for (i = 0; i < n; i++)
        printf("%s\n", words[i]);

    return 0;
}
Output :
Unsorted words: 
dog
cat
apple
banana
zebra
horse

Sorted words in lexicographical order: 
apple
banana
cat
dog
horse
zebra
* In this example, the program initializes an array of words, and uses nested loops to compare each pair of words in the array using the strcmp () function, which returns a negative, zero, or positive value if the first string is lexicographically less than, equal to, or greater than the second string, respectively.

* If a word comes before another word in lexicographical order, the program uses the strcpy () function to swap the two words. Finally, the program prints the unsorted and sorted words.