What is qsort in c

Last updated: April 1, 2026

Quick Answer: qsort() is a standard C library function that sorts arrays using the quicksort algorithm. Defined in stdlib.h, it accepts a pointer to an array, element count, element size, and a comparison function, making it work with any data type.

Key Facts

Overview

qsort() is a fundamental sorting function in the C standard library that provides an efficient, general-purpose sorting mechanism for arrays of any data type. Located in stdlib.h, this function implements the quicksort algorithm, one of the most efficient sorting algorithms for general-purpose use. The function's flexibility comes from its use of comparison functions, allowing developers to sort different data types and define custom sorting criteria without modifying the core algorithm.

Function Syntax

void qsort(void *ptr, size_t count, size_t size, int (*compare)(const void *, const void *));

Parameters:

Comparison Function

The comparison function is critical to qsort() operation. It receives pointers to two array elements and must return:

For integers, a simple comparison function might be: int compare(const void *a, const void *b) { return *(int*)a - *(int*)b; }

Algorithm Details

qsort() uses the quicksort algorithm, which has average time complexity of O(n log n) and space complexity of O(log n) for recursion. In worst-case scenarios (rare with proper pivot selection), complexity approaches O(n²). The in-place sorting nature of qsort() makes it memory-efficient for large arrays.

Practical Usage

qsort() is widely used for sorting arrays of integers, floating-point numbers, strings, and complex data structures. It's part of every C compiler's standard library, making it universally available. However, modern C++ programs often prefer std::sort() from the Standard Template Library for type-safety and potentially better performance.

Related Questions

How do I use qsort() to sort strings in C?

Create an array of string pointers (char*) and use a comparison function that calls strcmp() on the strings: int compare(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); } Then call qsort() with the array pointer, element count, size of char*, and comparison function.

What's the difference between qsort() and bsearch() in C?

qsort() sorts an array in-place using the quicksort algorithm, while bsearch() performs binary search on an already-sorted array. bsearch() requires the array to be pre-sorted and finds specific elements, whereas qsort() arranges all elements in order.

Why should I use qsort() instead of writing my own sorting algorithm?

qsort() is optimized, well-tested, and part of the standard library. It eliminates the need to implement sorting logic, reduces bugs, and typically performs better than custom implementations. Using library functions is a best practice in C programming.

Sources

  1. C Reference - qsort() CC-BY-SA-3.0
  2. Wikipedia - Quicksort Algorithm CC-BY-SA-4.0