Sorting Basics in C

Intermediate
8 min read
Updated: Nov 2026
2 examples

Order, Stability, and qsort

Sorting needs a comparison rule. C's qsort takes a comparator that returns negative, zero, or positive. Key properties of a sorting algorithm are its time complexity, whether it is in place, and whether it is stable (equal keys keep their input order). Stability matters when sorting records by one field after another.

Remember
int cmp(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}
qsort(arr, n, sizeof arr[0], cmp);

Cheat Sheet

Keep these facts handy while you work with Sorting Basics in C in C.

TopicDetail
ComparatorNegative, zero, or positive
In placeO(1) extra space
StableEqual keys keep order
qsort<stdlib.h>, not guaranteed stable

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Bubble Sort.

Example 1 — qsort ascending and descending

Only the comparator changes.

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

static int asc(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}
static int desc(const void *a, const void *b) { return asc(b, a); }

int main(void) {
    int a[] = {5, 2, 9, 1};
    qsort(a, 4, sizeof a[0], asc);
    printf("ascending: %d %d %d %d\n", a[0], a[1], a[2], a[3]);
    qsort(a, 4, sizeof a[0], desc);
    printf("descending: %d %d %d %d\n", a[0], a[1], a[2], a[3]);
    return 0;
}

How It Works

  1. The comparator returns -1, 0, or 1 without subtracting, which avoids overflow.
  2. desc just swaps the arguments.
  3. qsort works on any element type given a size and comparator.

Example 2 — A stable sort keeps ties in order

Insertion sort by score keeps Ann before Cy.

C
#include <stdio.h>

struct Rec { const char *name; int score; };

int main(void) {
    struct Rec r[] = {{"Ann", 90}, {"Bob", 85}, {"Cy", 90}, {"Di", 85}};
    int n = 4;

    for (int i = 1; i < n; i++) {
        struct Rec key = r[i];
        int j = i - 1;
        while (j >= 0 && r[j].score > key.score) {
            r[j + 1] = r[j];
            j--;
        }
        r[j + 1] = key;
    }
    for (int i = 0; i < n; i++) printf("%s %d\n", r[i].name, r[i].score);
    return 0;
}

How It Works

  1. Elements shift only while strictly greater, so equal scores never pass each other.
  2. Bob stays before Di and Ann stays before Cy.
  3. Using >= in the shift test would break stability.

Edge Cases & Pitfalls

Check these before relying on Sorting Basics in C in real programs.

sub

Subtraction comparators

return x - y; can overflow for large ints. Use (x > y) - (x < y).

void

Wrong cast in comparator

Cast const void * to the element type, not a pointer to pointer.

Key Takeaways

  • Comparator defines order.
  • Stability keeps ties.
  • qsort is not stable.

One line: Sorting needs a comparison rule.

Frequently Asked Questions

qsort sorts an array of any type using your comparison function, which returns negative, zero, or positive for less, equal, or greater.
A stable sort preserves the relative order of equal elements; an unstable sort may reorder them.
Continue with "C Bubble Sort" next. Repeatedly swap adjacent out-of-order items; trace each pass. The C Sorting Algorithms hub lists every topic in order.

Next: Bubble Sort

Repeatedly swap adjacent out-of-order items; trace each pass.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

8 people found this page helpful