C Online Compiler
Example: String Sorting using qsort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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; }
Output
Clear
ADVERTISEMENTS