TalentJR

⚙️ C programming basics · Class 10 · Lesson 15 of 18 · Free

Sorting Algorithms in C – Bubble, Selection, Insertion and qsort

⏱ About 40 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Write bubble sort, selection sort and insertion sort and trace each pass
  • Explain why these simple sorts slow down a lot on big lists (O(n²))
  • Sort arrays of numbers and structs with the library function qsort

The class teacher has 40 answer sheets and must arrange them by marks for the merit list. She could pick the highest each time, or swap neighbours that are in the wrong order, or slide each new sheet into its place. Those three habits are exactly the three classic sorting algorithms you write in this lesson.

How does bubble sort work in C?

Bubble sort walks through the array and swaps neighbours that are in the wrong order. After one pass, the biggest value has "bubbled" to the end.

Each pass puts one more value in its final place, so the inner loop can stop earlier each time (`n - 1 - pass`).

If a whole pass makes no swap, the array is already sorted and we stop early. Try it: start with an already sorted array and count the passes.

⚙️ C — you can edit this code
Output
After pass 1: 25 64 12 47 90 
After pass 2: 25 12 47 64 90 
After pass 3: 12 25 47 64 90 
After pass 4: 12 25 47 64 90 

How does selection sort work in C?

Selection sort finds the smallest value in the unsorted part and swaps it to the front. Then it repeats for the rest.

It makes at most one swap per pass. That helps when swapping is costly, like moving heavy records.

Here it sorts cricket scores from low to high. Try it: change `<` to `>` in the inner if, to sort from high to low.

⚙️ C — you can edit this code
Output
Pass 1: 10 29 14 37 13 
Pass 2: 10 13 14 37 29 
Pass 3: 10 13 14 37 29 
Pass 4: 10 13 14 29 37 

What is insertion sort in C?

Insertion sort works like arranging playing cards in your hand. Take the next card and slide it left until it is in the right place.

Bigger values move one step right to make space. Then the saved value drops into the gap.

Insertion sort is very fast on arrays that are almost sorted, so real libraries use it for small pieces. Try it: add two more fees to the array.

⚙️ C — you can edit this code
Output
Fees from low to high: 300 800 950 1200 1500

💡 sizeof fees / sizeof fees[0] counts the elements, so you do not have to update n by hand.

Why are bubble sort and selection sort slow?

Bubble and selection sort compare almost every pair of values. For n items that is about n × n / 2 comparisons. We write this as O(n²), read "order n squared".

This program counts the comparisons of bubble sort on a list in reverse order. Watch what happens when n grows 10 times.

Ten times more data means about 100 times more work. Fast sorts such as merge sort and quicksort need only about n × log n steps, which is why big programs use them.

⚙️ C — you can edit this code
Output
n =   10:      45 comparisons
n =  100:    4950 comparisons
n = 1000:  499500 comparisons

How do you use qsort in C?

C's standard library already has a fast sort: `qsort` in <stdlib.h>. You give it the array, the number of items, the size of one item, and a compare function.

The compare function is a function pointer (Lesson 9). It gets two `const void *` pointers, and returns a negative number if the first should come first, positive if second, and 0 if equal.

Here it sorts students by marks, highest first, and by name when marks are equal. Try it: sort by name only, using strcmp.

⚙️ C — you can edit this code
Output
1. Ananya  95
2. Dev     81
3. Kabir   81
4. Isha    67

💡 y->marks - x->marks is safe for marks; for huge numbers, compare with < and > instead to avoid overflow.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. This is ONE pass of bubble sort. What does it print?

int a[] = { 5, 1, 4, 2 };
for (int j = 0; j < 3; j++) {
    if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
}
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);

Question 2. This is the first pass of selection sort. What does it print?

int a[] = { 29, 10, 14, 37, 13 };
int min = 0;
for (int j = 1; j < 5; j++) if (a[j] < a[min]) min = j;
int t = a[0]; a[0] = a[min]; a[min] = t;
printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);

Question 3. The compare function returns b − a. What does this print?

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

int cmp(const void *a, const void *b) {
    return *(const int *)b - *(const int *)a;
}

int main(void) {
    int m[] = { 3, 1, 2 };
    qsort(m, 3, sizeof m[0], cmp);
    printf("%d %d %d\n", m[0], m[1], m[2]);
    return 0;
}

🧩 Your challenge

Read 5 runs scored by a batter in 5 matches. Sort them from HIGH to LOW with your own selection sort (not qsort), then print the sorted list, the best score and the median (the middle value). Example for inputs 34 78 12 56 90: Sorted: 90 78 56 34 12 Best: 90 Median: 56

Expected output (with the inputs given):
Runs in match 1: 34
Runs in match 2: 78
Runs in match 3: 12
Runs in match 4: 56
Runs in match 5: 90
Sorted: 90 78 56 34 12
Best: 90
Median: 56
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

int a[] = { 7, 3 };
if (a[0] > a[1]) {
    a[0] = a[1];
    a[1] = a[0];
}
printf("%d %d\n", a[0], a[1]);

Compiles and runs, but prints: 3 3 ⏎

✅ Right

int a[] = { 7, 3 };
if (a[0] > a[1]) {
    int temp = a[0];
    a[0] = a[1];
    a[1] = temp;
}
printf("%d %d\n", a[0], a[1]);

The first line overwrites 7 with 3, so the old value is lost before it is copied. A swap needs a temp variable to hold one value.

❌ Wrong

int a[] = { 5, 1, 4, 2 };
int n = 4;
for (int j = 0; j < n - 1; j++) {
    if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");

Compiles and runs, but prints: 1 4 2 5 ⏎

✅ Right

int a[] = { 5, 1, 4, 2 };
int n = 4;
for (int pass = 0; pass < n - 1; pass++) {
    for (int j = 0; j < n - 1 - pass; j++) {
        if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
    }
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");

One pass only moves the biggest value to the end. Bubble sort needs up to n − 1 passes, so it needs two loops.

❌ Wrong

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

int cmp(int *a, int *b) {
    return *a - *b;
}

int main(void) {
    int m[] = { 3, 1, 2 };
    qsort(m, 3, sizeof m[0], cmp);
    printf("%d %d %d\n", m[0], m[1], m[2]);
    return 0;
}

Line 10: error: incompatible function pointer types passing 'int (int *, int *)' to parameter of type 'int (*)(const void *, const void *)' [-Wincompatible-fun…

✅ Right

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

int cmp(const void *a, const void *b) {
    return *(const int *)a - *(const int *)b;
}

int main(void) {
    int m[] = { 3, 1, 2 };
    qsort(m, 3, sizeof m[0], cmp);
    printf("%d %d %d\n", m[0], m[1], m[2]);
    return 0;
}

qsort needs a function that takes two const void * pointers. Take them as void pointers and cast inside. This compiler stops with an error; some older compilers only warn.

📌 Remember

  • Bubble sort swaps wrong-order neighbours; each pass moves the biggest value to the end.
  • Selection sort picks the smallest value and swaps it to the front, one swap per pass.
  • Insertion sort slides each value left into place; it is fast on nearly sorted data.
  • All three are O(n²): 10 times more data means about 100 times more work.
  • Use qsort with a compare function for real programs; it works on any type, even structs.

Finished the quiz and the challenge?

Questions students ask

Which sorting algorithm is the fastest?

For big lists, algorithms like quicksort and merge sort (about n × log n steps) beat the O(n²) sorts by far. For very small or nearly sorted lists, insertion sort is often fastest. In C, just use qsort unless you have a reason not to.

Is qsort always quicksort?

No. The C standard only says qsort sorts the array; each library picks its own method. It is also not stable: equal items may change order, so add a tie-breaker (like the name) if order matters.

What does stable sorting mean?

A stable sort keeps items with equal keys in their original order. Bubble sort and insertion sort are stable; selection sort usually is not.

Why learn bubble sort if nobody uses it?

It teaches the basic ideas: comparing, swapping, loops inside loops and counting work. Those ideas are what you need to understand faster algorithms later.