cyberangles blog

C `qsort()` vs C++ `sort()`: A Comprehensive Comparison

Sorting is a fundamental operation in computer science, used in various applications ranging from simple data processing to complex algorithms. In the C and C++ programming languages, there are built - in functions to perform sorting operations: qsort() in C and sort() in C++. This blog post aims to provide a detailed comparison between these two sorting functions, covering their syntax, performance, usage scenarios, and more.

2026-07

Table of Contents#

  1. Syntax and Basic Usage
  2. Performance Comparison
  3. Usage Scenarios
  4. Handling Complex Data Types
  5. Common Practices and Best Practices
  6. Conclusion
  7. References

Syntax and Basic Usage#

C qsort()#

The qsort() function is defined in the <stdlib.h> header file. The syntax of qsort() is as follows:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
  • 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 bytes.
  • compar: A pointer to a comparison function that compares two elements. This function should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Here is an example of sorting an array of integers using qsort():

#include <stdio.h>
#include <stdlib.h>
 
// Comparison function for integers
int compare_ints(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}
 
int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
 
    qsort(arr, n, sizeof(int), compare_ints);
 
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
 
    return 0;
}

C++ sort()#

The sort() function is defined in the <algorithm> header file. The syntax of sort() is as follows:

template< class RandomIt >
void sort( RandomIt first, RandomIt last );
 
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • first, last: Iterators defining the range [first, last) of elements to sort.
  • comp: An optional binary comparison function object that returns true if the first argument should be ordered before the second.

Here is an example of sorting an array of integers using sort():

#include <iostream>
#include <algorithm>
#include <vector>
 
int main() {
    std::vector<int> arr = {5, 3, 8, 4, 2};
    std::sort(arr.begin(), arr.end());
 
    for (int num : arr) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
 
    return 0;
}

Performance Comparison#

  • Algorithm: qsort() typically uses the quicksort algorithm, which has an average time complexity of $O(n log n)$ but a worst - case time complexity of $O(n^2)$ when the input is already sorted or nearly sorted. sort() in C++ uses a hybrid sorting algorithm called introsort, which is a combination of quicksort, heapsort, and insertion sort. Introsort has an average and worst - case time complexity of $O(n log n)$.
  • Overhead: qsort() uses a function pointer for the comparison function, which can introduce some overhead during function calls. sort() is a template function, and the comparison can be inlined, reducing the overhead.

In general, for large datasets, sort() in C++ is likely to be more efficient than qsort() in C due to its better algorithm and reduced overhead.

Usage Scenarios#

  • C Projects: If you are working on a pure C project, you have no choice but to use qsort(). qsort() is also useful when you need to work with raw memory and arrays, as it can handle any data type.
  • C++ Projects: In C++ projects, sort() is the preferred choice. It is more type - safe, easier to use with the Standard Template Library (STL) containers, and generally more efficient.

Handling Complex Data Types#

C qsort()#

To sort an array of complex data types using qsort(), you need to define a proper comparison function. For example, sorting an array of structures:

#include <stdio.h>
#include <stdlib.h>
 
typedef struct {
    int id;
    char name[20];
} Person;
 
// Comparison function for Person structures based on id
int compare_persons(const void *a, const void *b) {
    Person *p1 = (Person *)a;
    Person *p2 = (Person *)b;
    return p1->id - p2->id;
}
 
int main() {
    Person people[] = {{2, "John"}, {1, "Alice"}, {3, "Bob"}};
    int n = sizeof(people) / sizeof(people[0]);
 
    qsort(people, n, sizeof(Person), compare_persons);
 
    for (int i = 0; i < n; i++) {
        printf("%d %s\n", people[i].id, people[i].name);
    }
 
    return 0;
}

C++ sort()#

In C++, you can use lambda functions or functor classes to sort containers of complex data types. For example, sorting a vector of Person objects:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
 
struct Person {
    int id;
    std::string name;
};
 
int main() {
    std::vector<Person> people = {{2, "John"}, {1, "Alice"}, {3, "Bob"}};
 
    std::sort(people.begin(), people.end(), [](const Person& p1, const Person& p2) {
        return p1.id < p2.id;
    });
 
    for (const auto& person : people) {
        std::cout << person.id << " " << person.name << std::endl;
    }
 
    return 0;
}

Common Practices and Best Practices#

C qsort()#

  • Error handling: qsort() does not return an error code. You need to ensure that the input parameters are valid to avoid undefined behavior.
  • Comparison function: Make sure the comparison function follows the correct rules of returning less than, equal to, or greater than zero.

C++ sort()#

  • Use lambda functions: For simple comparison criteria, lambda functions are a concise and convenient way to define the comparison.
  • Use STL containers: sort() works seamlessly with STL containers like std::vector, std::array, etc. Use these containers instead of raw arrays for better type - safety and functionality.

Conclusion#

Both qsort() in C and sort() in C++ are powerful sorting functions. qsort() is a legacy function that is useful in pure C projects and when working with raw memory. On the other hand, sort() in C++ is more type - safe, easier to use with STL containers, and generally more efficient due to its better algorithm and reduced overhead. When working on a C++ project, it is recommended to use sort() whenever possible.

References#