C qsort() Function

The qsort() function in C is a standard library function that sorts the elements of an array. It is part of the C standard library (stdlib.h). This function uses the quicksort algorithm, which is efficient and widely used for sorting arrays.

Table of Contents

  1. Introduction
  2. qsort() Function Syntax
  3. Understanding qsort() Function
  4. Examples
    • Sorting an Array of Integers
    • Sorting an Array of Structs
  5. Real-World Use Case
  6. Conclusion

Introduction

The qsort() function sorts the elements of an array in ascending order using the quicksort algorithm. This function is highly efficient and can be used to sort arrays of various data types by providing an appropriate comparison function.

qsort() Function Syntax

The syntax for the qsort() function is as follows:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

Parameters:

  • base: A pointer to the first element of the array to be sorted.
  • nmemb: The number of elements in the array.
  • size: The size of each element in the array.
  • compar: A comparison function that compares two elements. It should return:
    • A negative value if the first element is less than the second.
    • Zero if the two elements are equal.
    • A positive value if the first element is greater than the second.

Returns:

  • The qsort() function does not return a value.

Understanding qsort() Function

The qsort() function sorts the elements of an array in-place. The array elements can be of any type, and the sorting order is determined by the comparison function provided. The comparison function should take two const void * arguments and return an integer based on the comparison.

Examples

Sorting an Array of Integers

To demonstrate how to use qsort() to sort an array of integers, we will write a simple program.

Example

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

int compare_ints(const void *a, const void *b) {
    int int_a = *((int*)a);
    int int_b = *((int*)b);

    if (int_a < int_b) return -1;
    else if (int_a > int_b) return 1;
    else return 0;
}

int main() {
    int array[] = {7, 2, 5, 3, 8, 4, 6, 1, 9, 0};
    size_t n = sizeof(array) / sizeof(array[0]);

    // Sort the array
    qsort(array, n, sizeof(int), compare_ints);

    // Print the sorted array
    printf("Sorted array: ");
    for (size_t i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0;
}

Output:

Sorted array: 0 1 2 3 4 5 6 7 8 9

Sorting an Array of Structs

This example shows how to use qsort() to sort an array of structs.

Example

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

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

int compare_persons(const void *a, const void *b) {
    Person *person_a = (Person*)a;
    Person *person_b = (Person*)b;

    return strcmp(person_a->name, person_b->name);
}

int main() {
    Person people[] = {
        {1, "Alice"},
        {2, "Charlie"},
        {3, "Bob"},
        {4, "Diana"},
        {5, "Eve"}
    };
    size_t n = sizeof(people) / sizeof(people[0]);

    // Sort the array
    qsort(people, n, sizeof(Person), compare_persons);

    // Print the sorted array
    printf("Sorted array of people by name:\n");
    for (size_t i = 0; i < n; i++) {
        printf("ID: %d, Name: %s\n", people[i].id, people[i].name);
    }

    return 0;
}

Output:

Sorted array of people by name:
ID: 1, Name: Alice
ID: 3, Name: Bob
ID: 2, Name: Charlie
ID: 4, Name: Diana
ID: 5, Name: Eve

Real-World Use Case

Sorting Records in a Database

In real-world applications, the qsort() function can be used to sort records in a database. For example, you could use qsort() to sort an array of user records by their usernames or IDs.

Example: Sorting User Records by ID

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

typedef struct {
    int user_id;
    char username[30];
} User;

int compare_users(const void *a, const void *b) {
    User *user_a = (User*)a;
    User *user_b = (User*)b;

    return user_a->user_id - user_b->user_id;
}

int main() {
    User users[] = {
        {105, "kalpesh"},
        {102, "suresh"},
        {101, "ramesh"},
        {103, "mahesh"},
        {104, "naresh"}
    };
    size_t n = sizeof(users) / sizeof(users[0]);

    // Sort the array by user_id
    qsort(users, n, sizeof(User), compare_users);

    // Print the sorted array
    printf("Sorted array of users by user_id:\n");
    for (size_t i = 0; i < n; i++) {
        printf("User ID: %d, Username: %s\n", users[i].user_id, users[i].username);
    }

    return 0;
}

Output:

Sorted array of users by user_id:
User ID: 101, Username: ramesh
User ID: 102, Username: suresh
User ID: 103, Username: mahesh
User ID: 104, Username: naresh
User ID: 105, Username: kalpesh

Conclusion

The qsort() function is used for sorting arrays in C. By understanding and using this function correctly, you can efficiently sort arrays of various data types. The flexibility provided by the comparison function allows you to define custom sorting criteria, making qsort() suitable for a wide range of applications. Always ensure that the comparison function correctly defines the sorting order to get accurate results.

Comments