C Online Compiler
Example: Sorting Names using qsort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sorting Names using qsort #include <stdio.h> #include <string.h> // Required for strcmp #include <stdlib.h> // Required for qsort #define MAX_NAMES 5 // Comparison function required by qsort // It takes two const void pointers, which qsort will cast to the type of array elements int compareStrings(const void *a, const void *b) { // Step 1: Cast the void pointers to char** // This allows us to dereference them to get the actual char* (string) const char **str_a = (const char **)a; const char **str_b = (const char **)b; // Step 2: Use strcmp to compare the actual strings return strcmp(*str_a, *str_b); } int main() { // Step 3: Initialize an array of string pointers char *names[MAX_NAMES] = { "Charlie", "Alice", "Bob", "David", "Eve" }; int i; // Step 4: Print the original list of names printf("Original names:\n"); for (i = 0; i < MAX_NAMES; i++) { printf("%s\n", names[i]); } printf("\n"); // Step 5: Call qsort // Parameters: // 1. base: Pointer to the first element of the array to be sorted. // 2. num: Number of elements in the array. // 3. size: Size in bytes of each element in the array. // 4. compar: Pointer to a comparison function. qsort(names, MAX_NAMES, sizeof(char *), compareStrings); // Step 6: Print the sorted list of names printf("Sorted names (qsort):\n"); for (i = 0; i < MAX_NAMES; i++) { printf("%s\n", names[i]); } return 0; }
Output
Clear
ADVERTISEMENTS