✓ Link copied to clipboard
C 📅 July 12, 2026 ⏱ 6 min read

C Program to Sort Elements in Lexicographical Order

C Program to Sort Elements in Lexicographical Order

If you've ever organized your books alphabetically, you’ve pretty much sorted them in lexicographical order. This program does the same thing for strings. Let’s sort a few names and check it out.

Prerequisites for Sorting Elements in Lexicographical Order in C

Before diving into the code, ensure you have:

  • Familiarity with <stdio.h> and <string.h>
  • Understanding of for loops and arrays
  • Any C compiler such as GCC 9 or newer — or just run it in the EduSeekho online compiler

Source Code of C Program to Sort Elements in Lexicographical Order

Here is the C code that sorts strings in lexicographical order.

sort_lexico.cC▶ Run
#include <stdio.h>
#include <string.h>

void swap(char *str1, char *str2) {
    char temp[100];
    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);
}

int main() {
    int n;
    char str[10][100];
    printf("Enter number of strings: ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        printf("Enter string %d: ", i + 1);
        scanf("%s", str[i]);
    }

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (strcmp(str[i], str[j]) > 0) {
                swap(str[i], str[j]);
            }
        }
    }

    printf("Strings in lexicographical order:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", str[i]);
    }

    return 0;
}

Try this code yourself — free

Run it in the EduSeekho online compiler. No setup needed.

▶ Open Compiler

Output of the Sort Elements in Lexicographical Order Program

Here's what happens when you run this code and input some sample data.

TERMINALoutput
Enter number of strings: 3
Enter string 1: apple
Enter string 2: banana
Enter string 3: apricot
Strings in lexicographical order:
apple
apricot
banana
Output of C Program to Sort Elements in Lexicographical Order (Dictionary Order)
Output of C Program to Sort Elements in Lexicographical Order (Dictionary Order)

Algorithm to Sort Elements in Lexicographical Order in C

Sorting strings in lexicographical order involves comparing each pair and swapping them if they're out of order. Here's the step-by-step logic we use.

  1. Read the number of strings, n, from the user.
  2. Read each string into an array.
  3. Use nested loops to compare each pair of strings.
  4. If the current string comes after the next one in order, swap them.
  5. Repeat until no more swaps are needed.
  6. Print the sorted list of strings.
flowchart TD
  A([Start]) --> B[/Read number of strings n/]
  B --> C[/Read each string into array/]
  C --> D["for i from 0 to n-2"]
  D --> E["for j from i+1 to n-1"]
  E --> F{"strcmp(array[i], array[j]) > 0?"}
  F -->|Yes| G["swap array[i] and array[j]"]
  F -->|No| H
  G --> H["continue loop"]
  H --> E
  E --> D
  D --> I([End])
Flowchart: the algorithm step by step

How the Lexicographical Order Sorting Works

This section outlines how each part of the code functions to sort the strings.

  • #include <stdio.h> and #include <string.h>: Import the standard I/O and string manipulation libraries.
  • void swap(char *str1, char *str2): A helper function to swap two strings using a temporary storage technique.
  • int main(): The program starts executing from here.
  • int n: Stores the number of strings the user will input.
  • char str[10][100]: A 2D array to store up to 10 strings of 100 characters each.
  • scanf("%d", &n): Reads the number of strings.
  • for (int i = 0; i < n; i++): Loops through each string for input.
  • scanf("%s", str[i]): Reads each string from the user.
  • for (int i = 0; i < n - 1; i++): Outer loop for the sorting process.
  • for (int j = i + 1; j < n; j++): Inner loop to compare strings.
  • strcmp(str[i], str[j]): Compares two strings and returns a positive value if the first string is lexicographically greater.
  • swap(str[i], str[j]): Swaps strings if they are out of order.
  • printf(): Outputs the sorted strings.
  • return 0: Ends the program.
🧠

Quick Quiz — test your understanding

Tap an option to check your answer

What function is used to compare two strings in C?

🎉Correct! strcmp() is used to compare two strings.
🤔Not quite. Think about which function checks the order of characters.

How Fast Is the Sort Elements in Lexicographical Order Program in C?

Let's see how the time and space requirements shape up.

Time Complexity: O(n²). Here, n is the number of strings. This complexity arises from the two nested loops: for (int i = 0; i < n - 1; i++) and for (int j = i + 1; j < n; j++). It means if you have 10 strings, the program might run 100 comparisons.

Space Complexity: O(1). We use only a constant amount of additional space: the temporary array temp for swapping, no matter how big the input list is.

⚠️

Common mistake: Not swapping strings with a temporary array can mess up your outputs.

Key takeaway: To sort strings lexicographically, you need to compare and maybe swap each string pair.

FAQs About Sorting Elements in Lexicographical Order in C

These are some common questions about sorting strings in C.

The strcmp() function checks two strings in a lexicographical way. It gives you a negative, zero, or positive integer based on whether the first string's less than, equal to, or greater than the second string.
Yeah, you can use other sorting methods like quicksort or mergesort, but you’ll have to tweak them for strings.
The program can handle strings up to 99 characters long since the array is set up as char str[10][100].
Sure, you can sort numbers as strings to get lexicographical order, but that’s not the same as numeric order.
Lexicographical order is often used when sorting dictionaries, database entries, and search engine indexes.

If you found this program helpful, check out these related programs:

Conclusion

Sorting strings in C is a handy skill, especially for alphabetized data. You could try modifying the program to handle case sensitivity or longer strings for extra practice. For more challenges, check out sorting algorithms like quicksort.

Test your skills with our C programming quiz or run the program in the online compiler.