C Program For Sorting String In Alphabetical Order
Sorting strings alphabetically is a fundamental task in programming, crucial for organizing data like names, product lists, or dictionary entries. In this article, you will learn various C programming approaches to sort an array of strings in alphabetical (lexicographical) order.
Problem Statement
Imagine you have a collection of names or words, and you need to arrange them in alphabetical order. Without a systematic sorting method, such data would appear disorganized, making it difficult to search, analyze, or present effectively. The challenge is to implement an algorithm that can compare strings and rearrange them based on their lexicographical sequence.
Example
Consider an array of strings: {"banana", "apple", "cherry", "date"}.
After sorting in alphabetical order, the desired output would be: {"apple", "banana", "cherry", "date"}.
Background & Knowledge Prerequisites
To understand the solutions presented in this article, readers should have a basic understanding of:
- C Language Basics: Variables, data types, loops (for, while).
- Arrays: Declaring and manipulating one-dimensional arrays, especially character arrays (strings).
- Pointers: Basic concepts of pointers and their use in C, especially with strings.
- Functions: Defining and calling functions, including understanding function parameters and return types.
- String Manipulation: Familiarity with standard library functions like
strcmp()for string comparison andstrcpy()for string copying, both found in. -
stdlib.h: For theqsortfunction.
Use Cases
Sorting strings alphabetically is a widely applicable technique in various software domains:
- Data Presentation: Displaying lists of names, cities, or product categories in an organized manner for users.
- Search and Retrieval: Pre-sorting data can significantly speed up search algorithms (e.g., binary search) for text-based information.
- Dictionary and Glossary Management: Arranging words and their definitions in lexicographical order for easy navigation.
- File System Browsers: Listing files and directories alphabetically.
- Database Indexing: Optimizing database queries by sorting text-based fields.
Solution Approaches
We will explore two common approaches for sorting strings in C: a manual implementation using Bubble Sort for clarity, and a more efficient method leveraging the standard library's qsort function.
Approach 1: Bubble Sort for Strings
This approach demonstrates how to manually implement a sorting algorithm (Bubble Sort) tailored for strings using strcmp and strcpy.
- One-line summary: Compares adjacent strings and swaps them if they are in the wrong alphabetical order, repeating passes until no swaps are needed.
// String Sorting using Bubble Sort
#include <stdio.h>
#include <string.h> // For strcmp and strcpy
int main() {
// Step 1: Define the array of strings to be sorted
char strings[][20] = {"banana", "apple", "cherry", "date", "grape"};
int n = sizeof(strings) / sizeof(strings[0]); // Calculate number of strings
char temp[20]; // Temporary buffer for swapping strings
printf("Original strings:\\n");
for (int i = 0; i < n; i++) {
printf("%s\\n", strings[i]);
}
printf("\\n");
// Step 2: Implement Bubble Sort
// Outer loop for passes
for (int i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps in each pass
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent strings using strcmp
// strcmp returns < 0 if first string is smaller, > 0 if larger, 0 if equal
if (strcmp(strings[j], strings[j + 1]) > 0) {
// If strings[j] is alphabetically greater than strings[j+1], swap them
strcpy(temp, strings[j]); // Copy strings[j] to temp
strcpy(strings[j], strings[j + 1]); // Copy strings[j+1] to strings[j]
strcpy(strings[j + 1], temp); // Copy temp to strings[j+1]
}
}
}
// Step 3: Print the sorted strings
printf("Sorted strings (Bubble Sort):\\n");
for (int i = 0; i < n; i++) {
printf("%s\\n", strings[i]);
}
return 0;
}
Sample Output:
Original strings:
banana
apple
cherry
date
grape
Sorted strings (Bubble Sort):
apple
banana
cherry
date
grape
Stepwise Explanation:
- Initialization: An array of character arrays (
char strings[][20]) is declared to hold the strings.nstores the count of strings. Atempcharacter array is needed to facilitate swapping strings. - Bubble Sort Logic:
- The outer
forloop controls the number of passes, iteratingn-1times. - The inner
forloop iterates through the unsorted portion of the array. In each iteration, it compares two adjacent strings. - String Comparison:
strcmp(strings[j], strings[j + 1])is used to comparestrings[j]withstrings[j + 1]. - If
strcmpreturns a value greater than 0, it meansstrings[j]comes alphabetically *after*strings[j + 1]. - Swapping Strings: If
strings[j]needs to be moved afterstrings[j + 1], a swap operation is performed. Unlike integer swaps, strings must be copied usingstrcpy()because assigning character arrays directly is not possible.tempacts as a temporary holding place during this three-step copy process.
- Output: After the sorting loops complete, the program prints the strings in their new, sorted order.
Approach 2: Using qsort from Standard Library
The C standard library provides a generic sorting function qsort() in . This function is highly efficient (often implemented as Quick Sort) and can sort any array of elements, including strings, provided a custom comparison function is supplied.
- One-line summary: Employs the highly optimized
qsortfunction fromwith a user-defined comparison function to sort an array of strings.
// String Sorting using qsort
#include <stdio.h>
#include <stdlib.h> // For qsort
#include <string.h> // For strcmp
// Comparison function required by qsort
// It takes two void pointers to elements to be compared
int compareStrings(const void *a, const void *b) {
// Cast the void pointers to char pointers (pointers to strings)
const char *str1 = *(const char **)a;
const char *str2 = *(const char **)b;
// Use strcmp to compare the actual strings
return strcmp(str1, str2);
}
int main() {
// Step 1: Define the array of strings
char *strings[] = {"banana", "apple", "cherry", "date", "grape"};
int n = sizeof(strings) / sizeof(strings[0]);
printf("Original strings:\\n");
for (int i = 0; i < n; i++) {
printf("%s\\n", strings[i]);
}
printf("\\n");
// Step 2: Call qsort to sort the array of strings
// Parameters for qsort:
// 1. Base address of the array (strings)
// 2. Number of elements in the array (n)
// 3. Size of each element (sizeof(strings[0]) which is sizeof(char*))
// 4. Pointer to the comparison function (compareStrings)
qsort(strings, n, sizeof(strings[0]), compareStrings);
// Step 3: Print the sorted strings
printf("Sorted strings (qsort):\\n");
for (int i = 0; i < n; i++) {
printf("%s\\n", strings[i]);
}
return 0;
}
Sample Output:
Original strings:
banana
apple
cherry
date
grape
Sorted strings (qsort):
apple
banana
cherry
date
grape
Stepwise Explanation:
- Comparison Function (
compareStrings):
-
qsortrequires a comparison function that takes twoconst void *arguments (pointers to the elements being compared). - Inside
compareStrings, thesevoidpointers are cast toconst char **(pointer to a pointer to char), then dereferenced to getconst char *(actual string pointers). This is crucial becausestringsis an array ofchar*(string pointers), notchararrays directly. -
strcmp(str1, str2)is then called to perform the actual string comparison, and its result is returned directly, fulfillingqsort's requirement for a negative, zero, or positive return value.
mainFunction Initialization:
- An array of
char *(char *strings[]) is used here, where each element is a pointer to a string literal. This is a common and flexible way to handle collections of strings.
- Calling
qsort:
-
qsortis called with four arguments: -
strings: The base address of the array to be sorted. -
n: The number of elements in the array. -
sizeof(strings[0]): The size of each element in bytes. Sincestringsis an array ofchar *(pointers), this issizeof(char *). -
compareStrings: A pointer to our custom comparison function.
- Output: After
qsortcompletes its work, the strings in thestringsarray will be rearranged alphabetically. The program then iterates and prints the sorted array.
Conclusion
Sorting strings in alphabetical order is a foundational skill in C programming. We explored two primary approaches: a manual Bubble Sort implementation for conceptual understanding and the powerful qsort library function for efficient, practical applications. While manual sorting algorithms provide insight into how sorting works, qsort is generally preferred in production code due to its optimization and flexibility.
Summary
- Sorting strings alphabetically involves comparing them lexicographically and rearranging their order.
- The
strcmp()function fromis essential for comparing strings. - Bubble Sort is a straightforward algorithm to implement manually, involving nested loops and
strcpy()for swapping. - The
qsort()function fromprovides a highly optimized way to sort arrays of any data type, including strings. - When using
qsort()for strings, a custom comparison function is required that castsvoid *arguments tochar **and then usesstrcmp()to compare the actual string contents.