C qsort() Function

Beginner
7 min read
Updated: Nov 2026
3 examples
<stdlib.h>

Definition

The C qsort() function sorts an array in place. The library chooses the sorting algorithm. It calls the comparator with element pointers and arranges entries according to negative, zero, and positive results.

This function is declared in <stdlib.h>. Its contract matters as much as its call: validate every required precondition, check any documented sentinel, and keep ownership or host effects clear in the surrounding code. After a valid call, the array is ordered according to the comparator. There is no failure return; invalid sizes, pointers, or inconsistent comparators lead to invalid or undefined behavior. The examples below move from the direct call to an edge condition and a practical use.

Syntax

Start with this concrete qsort() call:

C
qsort(values, count, sizeof values[0], compare_int);
CallWhat it does
qsort(values, count, sizeof values[0], compare_int);Sorts an array in place using the concrete values shown.

Include <stdlib.h>. Also include headers that declare any types, limits, locale tools, or I/O functions used around the call.

Library declaration
C
void qsort(void *base, size_t count, size_t size, int (*compare)(const void *, const void *));

Parameters

ParameterDescription
baseFirst element of the array.
countNumber of elements.
sizeBytes per element.
compareComparator defining strict ordering.

Return Value

Return ValueDescription
No valueThe array is rearranged in place.

C Examples

Example 1 — Sort integers ascending

This complete program demonstrates a distinct part of the qsort() contract and checks the result or precondition that matters for the scenario.

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

static int compare_int(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;
    return (left > right) - (left < right);
}

int main(void) {
    int a[]={7,2,9,1}; size_t n=sizeof a/sizeof a[0];
    qsort(a,n,sizeof a[0],compare_int);
    for(size_t i=0;i<n;i++) printf("%d%s",a[i],i+1==n?"\n":" ");
    return 0;
}

How It Works

  1. Step 1. Create an unsorted array and count its elements.
  2. Step 2. Pass element size and a safe three-way comparator.
  3. Step 3. qsort() rearranges the original array in place.
  4. Step 4. Iterate over the now-ascending values.

Example 2 — Sort descending

This complete program demonstrates a distinct part of the qsort() contract and checks the result or precondition that matters for the scenario.

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

static int desc(const void *a,const void *b){int x=*(const int*)a,y=*(const int*)b;return (y>x)-(y<x);}
int main(void){int a[]={3,8,5};qsort(a,3,sizeof a[0],desc);printf("%d %d %d\n",a[0],a[1],a[2]);}

How It Works

  1. Step 1. Reverse the comparator's ordering decision.
  2. Step 2. Supply the same element width as the array type.
  3. Step 3. The largest element moves to the first position.
  4. Step 4. Print the reordered array to confirm descending order.

Example 3 — Sort structures by one field

This complete program demonstrates a distinct part of the qsort() contract and checks the result or precondition that matters for the scenario.

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

typedef struct { const char *name; int score; } Item;
static int by_score(const void *a,const void *b){const Item *x=a,*y=b;return (x->score>y->score)-(x->score<y->score);}
int main(void){Item a[]={{"Ada",9},{"Lin",4}};qsort(a,2,sizeof a[0],by_score);printf("%s first\n",a[0].name);}

How It Works

  1. Step 1. Define a structure with a sortable score field.
  2. Step 2. Cast comparator inputs back to structure pointers.
  3. Step 3. Compare scores without risky subtraction.
  4. Step 4. qsort() moves complete structure objects together.

Frequently Asked Questions

qsort() sorts an array in place. The library chooses the sorting algorithm. It calls the comparator with element pointers and arranges entries according to negative, zero, and positive results.
Include <stdlib.h> before calling qsort().
After a valid call, the array is ordered according to the comparator. There is no failure return; invalid sizes, pointers, or inconsistent comparators lead to invalid or undefined behavior.
A comparator must be consistent and avoid overflow. qsort() is not required to be stable, so equal elements may change relative order.
The function is specified by the C standard library. Exact limits, locale behavior, environment behavior, allocation capacity, or host effects can still vary where relevant.

Next: quick_exit()

Continue through the C stdlib.h tutorials.

quick_exit() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful