qsort() Function

The qsort() function in C is a versatile sorting utility that rearranges elements in an array in place using a user-defined comparison function. It is designed to work with any data type by allowing custom comparison logic, making it a fundamental tool for organizing data efficiently.


Syntax of qsort()

</>
Copy
void qsort(void *base, size_t num, size_t size, int (*compar)(const void*, const void*));

Parameters

ParameterDescription
basePointer to the first element of the array to be sorted, converted to a void*.
numNumber of elements in the array.
sizeSize in bytes of each element in the array.
comparPointer to a function that compares two elements. The function returns a negative value if the first element is less than the second, zero if they are equal, and a positive value if the first element is greater than the second.

The sorting algorithm implemented by qsort() repeatedly compares pairs of elements using the specified comparison function to determine their order. It rearranges the elements in place without returning a new array, and the relative order of equivalent elements is undefined.


Examples for qsort()

Example 1: Sorting an Integer Array in Ascending Order

This example demonstrates how to sort an array of integers in ascending order using qsort().

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int compareInts(const void *a, const void *b) {
    int int_a = *(const int *)a;
    int int_b = *(const int *)b;
    return int_a - int_b;
}

int main() {
    int arr[] = { 5, 3, 8, 1, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);

    qsort(arr, n, sizeof(int), compareInts);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

Explanation:

  1. An array of integers is defined and its size is computed.
  2. A comparison function compareInts() is implemented to compare two integers.
  3. qsort() is called to sort the array in ascending order based on the comparison function.
  4. The sorted array is printed to the console.

Output:

Sorted array: 1 2 3 5 8 9

Example 2: Sorting an Array of Strings in Lexicographical Order

This example shows how to sort an array of C strings in lexicographical (alphabetical) order using qsort().

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compareStrings(const void *a, const void *b) {
    const char *str_a = *(const char **)a;
    const char *str_b = *(const char **)b;
    return strcmp(str_a, str_b);
}

int main() {
    const char *arr[] = { "banana", "apple", "cherry", "date" };
    int n = sizeof(arr) / sizeof(arr[0]);

    qsort(arr, n, sizeof(const char *), compareStrings);

    printf("Sorted strings: ");
    for (int i = 0; i < n; i++) {
        printf("%s ", arr[i]);
    }
    printf("\n");
    return 0;
}

Explanation:

  1. An array of C strings is defined.
  2. A comparison function compareStrings() is implemented using strcmp() to compare two strings.
  3. qsort() is used to sort the array in lexicographical order.
  4. The sorted array of strings is printed.

Output:

Sorted strings: apple banana cherry date

Example 3: Sorting an Array of Structures by a Numeric Field

This example demonstrates how to sort an array of structures based on an integer field using qsort().

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[20];
} Person;

int comparePersons(const void *a, const void *b) {
    const Person *p1 = (const Person *)a;
    const Person *p2 = (const Person *)b;
    return p1->id - p2->id;
}

int main() {
    Person persons[] = { {3, "Arjun"}, {1, "Ram"}, {2, "Priya"} };
    int n = sizeof(persons) / sizeof(persons[0]);

    qsort(persons, n, sizeof(Person), comparePersons);

    printf("Sorted Persons by ID:\n");
    for (int i = 0; i < n; i++) {
        printf("ID: %d, Name: %s\n", persons[i].id, persons[i].name);
    }
    return 0;
}

Explanation:

  1. A Person structure is defined with an integer field and a string field.
  2. An array of Person structures is initialized with unsorted data.
  3. A comparison function comparePersons() is implemented to compare the id fields of two structures.
  4. qsort() sorts the array of structures based on the numeric field.
  5. The sorted array is printed, displaying each person’s ID and name.

Output:

Sorted Persons by ID:
ID: 1, Name: Ram
ID: 2, Name: Priya
ID: 3, Name: Arjun