Sorting Algorithms in C
Sorting puts data in order: marks from highest to lowest, names A to Z, products by price. In Sorting an Array in C you learned bubble sort and selection sort, which are easy but slow for big data (O(n²)). Professional programs use faster ideas.
In this lesson you will learn three important algorithms: insertion sort (great for small or nearly sorted data), merge sort (divide and conquer, always O(n log n)) and quick sort (the fastest in practice). You will see each one step by step, compare their complexity and stability, and learn which to choose.
What You Will Learn
- How insertion sort builds a sorted part one element at a time.
- How merge sort divides, sorts and merges.
- How quick sort partitions around a pivot.
- Best, average and worst-case time complexity.
- What stable and in-place sorting mean.
- Which sorting algorithm to use when, and the library
qsort().
Sorting Algorithms in C Explained
Exam definition: Sorting is arranging elements in ascending or descending order. Insertion sort takes elements one by one and inserts each into its correct place in the already-sorted part (O(n²) worst, O(n) best). Merge sort is a divide and conquer algorithm that splits the array into halves, sorts them recursively and merges the sorted halves (O(n log n) always, needs O(n) extra memory). Quick sort picks a pivot, partitions the array so smaller elements go left and larger go right, then sorts both parts recursively (O(n log n) average, O(n²) worst).
Memory trick: Insertion sort = arranging playing cards in your hand: pick a card and slide it into the right place. Merge sort = two teachers each sort half the answer sheets, then merge the two sorted piles by always taking the smaller top sheet. Quick sort = a PT teacher picks one student (the pivot) and says "shorter ones to my left, taller ones to my right", then repeats in each group.
Syntax: The Core Ideas
/* Insertion sort: shift bigger elements right, drop key into the gap */
for (i = 1; i < n; i++)
{
key = a[i];
for (j = i - 1; j >= 0 && a[j] > key; j--)
a[j + 1] = a[j];
a[j + 1] = key;
}
/* Merge sort */ merge_sort(a, low, high):
if low < high:
mid = (low + high) / 2
merge_sort(a, low, mid); merge_sort(a, mid + 1, high)
merge(a, low, mid, high)
/* Quick sort */ quick_sort(a, low, high):
if low < high:
p = partition(a, low, high) /* pivot in final place */
quick_sort(a, low, p - 1); quick_sort(a, p + 1, high)
| Algorithm | Best | Average | Worst | Extra space | Stable? |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) stack | No |
Example 1: Insertion Sort with Each Pass
#include <stdio.h>
void print_array(const int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
void insertion_sort(int a[], int n)
{
int i, j, key;
for (i = 1; i < n; i++)
{
key = a[i];
for (j = i - 1; j >= 0 && a[j] > key; j--)
a[j + 1] = a[j]; /* shift bigger elements right */
a[j + 1] = key; /* insert key in the gap */
printf("Pass %d (insert %d): ", i, key);
print_array(a, n);
}
}
int main(void)
{
int a[] = {29, 10, 14, 37, 13};
int n = 5;
printf("Start : ");
print_array(a, n);
insertion_sort(a, n);
return 0;
}
Output
Start : 29 10 14 37 13 Pass 1 (insert 10): 10 29 14 37 13 Pass 2 (insert 14): 10 14 29 37 13 Pass 3 (insert 37): 10 14 29 37 13 Pass 4 (insert 13): 10 13 14 29 37
Code Explanation
- The left part of the array is always sorted. At the start it is just the first element, 29.
- Each pass takes the next element (
key) and shifts every bigger element in the sorted part one place right. - Pass 1: 10 is smaller than 29, so 29 shifts right and 10 goes first.
- Pass 3: 37 is already bigger than 29, so nothing shifts. On nearly sorted data most passes are like this, which is why insertion sort's best case is O(n).
- Pass 4: 13 shifts 37, 29 and 14 to the right and lands after 10.
- Equal elements are never moved past each other (
a[j] > key, not>=), so insertion sort is stable.
How Merge Sort and Quick Sort Work
MERGE SORT on 38 27 43 3 9 82 10
split: [38 27 43 3] [9 82 10]
split: [38 27] [43 3] [9 82] [10]
split: [38][27] [43][3] [9][82] [10]
merge: [27 38] [3 43] [9 82] [10]
merge: [3 27 38 43] [9 10 82]
merge: [3 9 10 27 38 43 82]
QUICK SORT partition (pivot = last element = 10) on 38 27 43 3 9 82 10
elements < 10 go left: 3 9 | 10 | 27 43 38 82 -> 10 is in its final place
then quick sort [3 9] and [27 43 38 82] the same way
- Merge sort does the work while merging; splitting is trivial. It always has about log₂ n levels, each costing O(n): O(n log n) guaranteed.
- Quick sort does the work while partitioning; combining is trivial. If the pivot keeps splitting the array evenly, it is O(n log n). If the pivot is always the smallest or largest (e.g. already sorted data with the last element as pivot), it becomes O(n²).
Example 2: Merge Sort and Quick Sort
#include <stdio.h>
#define N 7
void print_array(const char *label, const int a[], int n)
{
int i;
printf("%s", label);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
/* ---------- merge sort ---------- */
void merge(int a[], int low, int mid, int high)
{
int temp[N];
int i = low, j = mid + 1, k = 0;
while (i <= mid && j <= high)
temp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++]; /* <= keeps it stable */
while (i <= mid)
temp[k++] = a[i++];
while (j <= high)
temp[k++] = a[j++];
for (k = 0, i = low; i <= high; i++, k++)
a[i] = temp[k];
}
void merge_sort(int a[], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
merge_sort(a, low, mid);
merge_sort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
/* ---------- quick sort (Lomuto partition) ---------- */
void swap(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}
int partition(int a[], int low, int high)
{
int pivot = a[high], i = low - 1, j;
for (j = low; j < high; j++)
if (a[j] < pivot)
swap(&a[++i], &a[j]);
swap(&a[i + 1], &a[high]); /* put pivot in its final place */
return i + 1;
}
void quick_sort(int a[], int low, int high)
{
int p;
if (low < high)
{
p = partition(a, low, high);
quick_sort(a, low, p - 1);
quick_sort(a, p + 1, high);
}
}
int main(void)
{
int m[N] = {38, 27, 43, 3, 9, 82, 10};
int q[N] = {38, 27, 43, 3, 9, 82, 10};
int p;
print_array("Original : ", m, N);
merge_sort(m, 0, N - 1);
print_array("Merge sorted : ", m, N);
p = partition(q, 0, N - 1);
printf("After 1st partition, pivot %d is at index %d\n", q[p], p);
print_array(" ", q, N);
quick_sort(q, 0, N - 1);
print_array("Quick sorted : ", q, N);
return 0;
}
Output
Original : 38 27 43 3 9 82 10
Merge sorted : 3 9 10 27 38 43 82
After 1st partition, pivot 10 is at index 2
3 9 10 38 27 82 43
Quick sorted : 3 9 10 27 38 43 82
mergewalks two sorted halves withiandj, always copying the smaller front element intotemp, then copiestempback. This needs O(n) extra memory.partitionkeepsias the end of the "smaller than pivot" zone. Every element less than 10 (3 and 9) is swapped into that zone; finally the pivot is swapped in after it, at index 2, its final sorted position.- Quick sort then sorts the left part [3 9] and the right part [38 27 82 43] separately, in place.
- Both give the same result; they differ in speed, memory and stability.
Which Sorting Algorithm Should You Use?
| Situation | Good choice |
|---|---|
| Small array (≈ 20 elements) or nearly sorted data | Insertion sort |
| Large data, need guaranteed O(n log n), or need stability | Merge sort |
| Large data in memory, fastest on average | Quick sort (with a good pivot) |
| Data too big for RAM (sorting files) | External merge sort |
| Everyday C programs | The library qsort() from <stdlib.h> |
Important Points to Remember
- Insertion sort: insert each element into the sorted left part; O(n²), but O(n) on nearly sorted data; stable, in place.
- Merge sort: divide, sort halves, merge; O(n log n) always; stable; needs O(n) extra memory.
- Quick sort: partition around a pivot; O(n log n) average, O(n²) worst; in place; not stable.
- Stable = equal elements keep their original order. In place = only O(1) or O(log n) extra memory.
- Merge sort and quick sort are divide and conquer algorithms.
- Choosing a random or median-of-three pivot avoids quick sort's worst case.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Insertion sort loop j >= 0 checked after a[j] | Reads a[-1] | Write j >= 0 && a[j] > key in that order |
| Forgetting to copy the leftovers in merge | Some elements disappear | Copy remaining elements of both halves |
Using < instead of <= in merge | Merge sort becomes unstable | Take from the left half on ties |
Recursing on quick_sort(a, low, p) | Infinite recursion when the pivot stays in place | Exclude the pivot: p - 1 and p + 1 |
| Quick sort with last-element pivot on sorted data | O(n²) and deep recursion | Pick a random or middle pivot |
Sorting Algorithms Practice Questions
- Explain insertion sort with an example. What is its best-case time?
- What is divide and conquer? Which sorting algorithms use it?
- Write the steps of merging two sorted arrays.
- What is a pivot? When does quick sort take O(n²) time?
- What is a stable sort? Which of insertion, merge and quick sort are stable?
Show answers
- Each element is inserted into its correct place in the sorted part on its left by shifting bigger elements right; best case O(n) when the array is already sorted.
- Splitting a problem into smaller subproblems, solving them recursively and combining the results; merge sort and quick sort.
- Compare the front elements of both arrays, copy the smaller into the result, advance in that array, repeat; then copy what is left of either array.
- The element used to partition the array (smaller to the left, larger to the right); O(n²) when the pivot is always the smallest or largest element, e.g. sorted input with the last element as pivot.
- A sort that keeps equal elements in their original relative order; insertion sort and merge sort are stable, quick sort is not.
Coding Exercise
Use the library function qsort() to sort an array of student structures by marks in descending order. Students: Asha 78, Vikram 91, Neel 65, Tara 88.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct student
{
char name[20];
int marks;
};
int by_marks_desc(const void *a, const void *b)
{
const struct student *x = a, *y = b;
return y->marks - x->marks; /* bigger marks first */
}
int main(void)
{
struct student s[] = {{"Asha", 78}, {"Vikram", 91}, {"Neel", 65}, {"Tara", 88}};
int n = 4, i;
qsort(s, n, sizeof s[0], by_marks_desc);
for (i = 0; i < n; i++)
printf("%d. %-7s %d\n", i + 1, s[i].name, s[i].marks);
return 0;
}
1. Vikram 91 2. Tara 88 3. Asha 78 4. Neel 65
qsort takes a comparison function that returns a negative, zero or positive number; reversing x and y gives descending order.
Quick Quiz: Sorting Algorithms (MCQ)
-
Which sort is O(n log n) in every case?
A) Quick sort B) Merge sort C) Insertion sort D) Bubble sort
-
Best-case time of insertion sort:
A) O(1) B) O(n) C) O(n log n) D) O(n²)
-
Which algorithm uses a pivot?
A) Merge sort B) Quick sort C) Insertion sort D) Selection sort
-
Which needs O(n) extra memory?
A) Insertion sort B) Quick sort C) Merge sort D) Bubble sort
-
Which of these is NOT stable?
A) Merge sort B) Insertion sort C) Quick sort D) Bubble sort
Show answers
- B: merge sort.
- B: O(n).
- B: quick sort.
- C: merge sort.
- C: quick sort.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Insertion sort | O(n²), best O(n), stable, in place |
|---|---|
| Merge sort | O(n log n) always, stable, O(n) extra |
| Quick sort | Avg O(n log n), worst O(n²), in place, not stable |
| Divide and conquer | Merge sort, quick sort |
| Pivot | Element used to partition in quick sort |
| Stable | Equal elements keep their order |
| Library | qsort() in stdlib.h |
Frequently asked questions
- Which is the best sorting algorithm?
- It depends: quick sort is fastest on average, merge sort guarantees O(n log n) and stability, insertion sort wins for small or nearly sorted data.
- What is the difference between merge sort and quick sort?
- Merge sort does its work while merging and needs extra memory; quick sort does its work while partitioning and sorts in place.
- Why is insertion sort fast on nearly sorted data?
- Each element moves only a few places, so the inner loop rarely runs: close to O(n).
Remember
- Insertion = playing cards; merge = two sorted piles; quick = PT teacher's pivot.
- Merge: always n log n. Quick: usually n log n.
Next Topic
Next lesson: Calculator Project in C. Module 17 begins: you will build your first complete project, a menu-driven calculator.