C Examples Lexicographical Order
## C Program to Sort Strings in Lexicographical Order
In computer science, **lexicographical order** (also known as alphabetical or dictionary order) is the generalization of the alphabetical order of the dictionaries to sequences of ordered symbols.
Sorting strings lexicographically is a fundamental operation in C programming. This tutorial demonstrates how to accept a list of strings from the user and sort them in alphabetical order using standard library functions.
---
### Understanding the Core Concepts
To sort strings in C, we rely on two key functions provided by the `` header file:
1. **`strcmp(str1, str2)`**: Compares two strings character by character based on their ASCII values.
- Returns `< 0` if `str1` is lexicographically smaller than `str2`.
- Returns `0` if `str1` is equal to `str2`.
- Returns `> 0` if `str1` is lexicographically larger than `str2`.
2. **`strcpy(dest, src)`**: Copies the content of the source string (`src`) to the destination buffer (`dest`). This is used to swap strings during the sorting process.
---
### Code Example: Sorting 10 Words Alphabetically
The following program prompts the user to enter 10 words, sorts them in ascending lexicographical order using the Bubble Sort algorithm, and displays the sorted list.
```c
#include
#include
int main()
{
int i, j;
// Declare a 2D char array to store 10 strings, each up to 49 characters + null terminator
char str, temp;
printf("Enter 10 words:\n");
// Read 10 strings from the user
for(i = 0; i < 10; ++i)
{
scanf("%s", str);
}
// Perform Bubble Sort to arrange strings lexicographically
for(i = 0; i < 9; ++i)
{
for(j = i + 1; j < 10; ++j)
{
// If the current string is lexicographically greater than the next string, swap them
if(strcmp(str, str) > 0)
{
strcpy(temp, str);
strcpy(str, str);
strcpy(str, temp);
}
}
}
printf("\nIn lexicographical order:\n");
for(i = 0; i < 10; ++i)
{
puts(str);
}
return 0;
}
```
---
### Sample Input and Output
#### Input:
```text
Enter 10 words:
C
C++
Java
PHP
Python
Perl
Ruby
R
JavaScript
PHP
```
#### Output:
```text
In lexicographical order:
C
C++
Java
JavaScript
PHP
PHP
Perl
Python
R
Ruby
```
---
### Code Explanation
1. **Two-Dimensional Array (`char str`)**:
We define a 2D array where `10` represents the maximum number of strings, and `50` represents the maximum length of each string (including the null terminator `\0`).
2. **Comparison (`strcmp`)**:
The nested loops compare adjacent elements. If `strcmp(str, str) > 0`, it means `str` should appear after `str` in alphabetical order.
3. **Swapping (`strcpy`)**:
Because arrays in C cannot be directly assigned using the `=` operator (e.g., `str = str` is invalid), we must use `strcpy()` to copy the string data into a temporary buffer (`temp`) to complete the swap.
---
### Key Considerations & Best Practices
* **Case Sensitivity**: The `strcmp()` function is case-sensitive because it compares ASCII values. In ASCII, all uppercase letters (`A-Z`, values `65-90`) come before lowercase letters (`a-z`, values `97-122`). For example, `"Zebra"` will be sorted *before* `"apple"`. To perform a case-insensitive sort, you can use platform-specific functions like `strcasecmp()` (POSIX) or `_stricmp()` (Windows).
* **Buffer Overflow Prevention**: Using `scanf("%s", str)` can be unsafe if the user inputs a word longer than 49 characters. To prevent buffer overflows, you can limit the input size using a width specifier: `scanf("%49s", str)`.
* **Handling Spaces**: `scanf("%s")` stops reading when it encounters whitespace. If you need to sort sentences or strings containing spaces, use `fgets(str, sizeof(str), stdin)` instead.
YouTip