Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding and Using the qsort Function in C

Tech 1

Introduction to qsort

qsort is a stnadard library function in C that implements a sorting algorithm, typical based on quicksort. It is designed to sort data of any type, making it a versatile tool for various applications.

Header File

To use qsort, include the following header:

#include <stdlib.h>

Function Parameters

qsort has the following prototype:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
  • base: Pointer to the first element of the array to be sorted.
  • nmemb: Number of elements in the array.
  • size: Size in bytes of each element.
  • compar: Pointer to a comparison function that defines the sort order.

qsort function parameters

qsort usage example

void pointer explanation

qsort function details

Note: The void* type is a generic pointer that can hold addresses of any data type. It cannot be directly dereferenced or used in pointer arithmetic without casting.

Sorting Integer Data with qsort

Here's an example of using qsort to sort an array of integers:

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

int compareIntegers(const void *a, const void *b) {
    // Method 1: Explicit comparison
    // int valA = *(int*)a;
    // int valB = *(int*)b;
    // if (valA > valB) return 1;
    // else if (valA < valB) return -1;
    // else return 0;

    // Method 2: Direct subtraction (for ascending order)
    return (*(int*)a - *(int*)b);
}

int main() {
    int numbers[] = {2, 4, 6, 8, 0, 9, 7, 5, 3, 1};
    int count = sizeof(numbers) / sizeof(numbers[0]);
    
    qsort(numbers, count, sizeof(int), compareIntegers);
    
    for (int i = 0; i < count; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");
    return 0;
}

Sorting Structure Data with qsort

qsort can also sort arrrays of structures. Below is an example with a student structure:

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

struct Student {
    char name[20];
    int age;
};

// Compare by age
int compareByAge(const void *a, const void *b) {
    return ((struct Student*)a)->age - ((struct Student*)b)->age;
}

// Compare by name
int compareByName(const void *a, const void *b) {
    return strcmp(((struct Student*)a)->name, ((struct Student*)b)->name);
}

void sortByAge() {
    struct Student students[] = {{"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15}};
    int count = sizeof(students) / sizeof(students[0]);
    
    qsort(students, count, sizeof(struct Student), compareByAge);
    
    for (int i = 0; i < count; i++) {
        printf("%d ", students[i].age);
    }
    printf("\n");
}

void sortByName() {
    struct Student students[] = {{"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15}};
    int count = sizeof(students) / sizeof(students[0]);
    
    qsort(students, count, sizeof(struct Student), compareByName);
    
    for (int i = 0; i < count; i++) {
        printf("%s ", students[i].name);
    }
    printf("\n");
}

int main() {
    sortByAge();
    sortByName();
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.