C qsort() vs C++ sort()

The qsort() function in C and sort() function in C++ are both used for sorting arrays, but they differ significantly in implementation, performance, and usage. Understanding these differences helps choose the right sorting approach for your program.

C qsort() Syntax

void qsort(void *base, size_t num, size_t size, int (*comparator)(const void*, const void*));

This function takes the base address of the array, number of elements, size of each element, and a comparator function.

C++ sort() Syntax

void sort(T first, T last, Compare c);

Here T represents iterators, and the order of repeated elements is not guaranteed to be preserved. For stable sorting, C++ provides stable_sort().

Example: Using qsort() in C

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

int compare(const void *a, const void *b) {
    int x = *(const int*)a;
    int y = *(const int*)b;
    return x - y;
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    qsort(arr, n, sizeof(int), compare);
    
    printf("\nSorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}
Original array: 64 34 25 12 22 11 90 
Sorted array: 11 12 22 25 34 64 90

Key Differences

qsort() in C sort() in C++
Uses quicksort algorithm Uses introsort (hybrid algorithm: introsort, quicksort, and insertion sort)
C standard doesn't specify time complexity Guaranteed O(n log n) worst case in C++11+, previous versions could be O(n²)
Slower execution time Faster execution time
Works only with C arrays Works with arrays, vectors, deques, and other STL containers
Uses unsafe void pointers Type-safe with templates
Requires custom comparator function Can use function objects, lambdas, or default comparison

Conclusion

While qsort() provides basic sorting functionality in C, C++ sort() offers better performance, type safety, and flexibility. The choice depends on the programming language and specific requirements of your application.

Updated on: 2026-03-15T10:33:37+05:30

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements