c
  1. c-program-to-sort-elements-in-lexicographical-order-dictionary-order

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

This program sorts the elements of an array in lexicographical order (dictionary order) using C programming language. The lexicographical order is the way in which words are ordered based on the alphabetical order of their component letters. This program uses the bubble sort algorithm to sort the elements in the array.

Syntax

void sortLexicographically(char arr[][MAX_SIZE], int n);

Example

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

#define MAX_SIZE 100

void sortLexicographically(char arr[][MAX_SIZE], int n);

int main()
{
    char arr[MAX_SIZE][MAX_SIZE];
    int n, i;

    printf("Enter the number of strings: ");
    scanf("%d", &n);

    printf("Enter %d strings: \n", n);
    for(i=0; i<n; i++)
    {
        scanf("%s", arr[i]);
    }

    sortLexicographically(arr, n);

    printf("\nSorted strings are:\n");
    for(i=0; i<n; i++)
    {
        printf("%s\n", arr[i]);
    }

    return 0;
}

void sortLexicographically(char arr[][MAX_SIZE], int n)
{
    int i, j;
    char temp[MAX_SIZE];

    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
            if(strcmp(arr[i], arr[j]) > 0)
            {
                strcpy(temp, arr[i]);
                strcpy(arr[i], arr[j]);
                strcpy(arr[j], temp);
            }
        }
    }
}

Output

Enter the number of strings: 4
Enter 4 strings:
hello
world
python
programming

Sorted strings are:
hello
programming
python
world

Explanation

This program prompts the user to enter the number of strings and then the strings themselves. It then sorts the strings in lexicographical order using the bubble sort algorithm and the strcmp() function. Finally, it prints the sorted strings to the console.

The strcmp() function is used to compare pairs of adjacent strings. If the first string is found to be greater than the second string in lexicographical order, they are swapped. This process is repeated until the strings are sorted in lexicographical order.

Use

This program can be used to sort the elements of an array in lexicographical order. It can be particularly useful when dealing with lists of words or strings in a C program.

Summary

In this tutorial, we wrote a program in C that sorts the elements of an array in lexicographical order (dictionary order) using the bubble sort algorithm. We covered the syntax, example, output, explanation, use, and important points of this program. By following this tutorial, you can have a better understanding of how to sort elements in an array in lexicographical order using C programming language.

Published on: