Reading history

Bubble, Selection and Insertion Sort in C

5 min read 2 views

Learn bubble sort, selection sort and insertion sort in C with working code, a step-by-step trace, time complexity, stability and when to use each.

Sorting puts items in order, such as numbers from smallest to largest or names from A to Z. It is one of the most studied problems in computer science, because sorted data makes searching, merging and finding duplicates far easier. This lesson covers the three classic simple sorts, bubble sort, selection sort and insertion sort, in C, with how each one works and when it is still a sensible choice.

In this lesson you will learn

  • How bubble, selection and insertion sort work
  • Implementing all three in C
  • Tracing insertion sort step by step
  • Their time and space complexity
  • What “stable” and “in-place” mean

Three Simple Sorts in C

#include <stdio.h>

void print_array(const int a[], int n) {
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
}

void bubble_sort(int a[], int n) {
    for (int pass = 0; pass < n - 1; pass++) {
        int swapped = 0;
        for (int j = 0; j < n - 1 - pass; j++) {
            if (a[j] > a[j + 1]) {          /* neighbours out of order */
                int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;               /* already sorted: stop early */
    }
}

void selection_sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[min]) min = j;     /* find smallest in the rest */
        int t = a[i]; a[i] = a[min]; a[min] = t;
    }
}

void insertion_sort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {     /* shift bigger items right */
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;                    /* drop key into the gap */
    }
}

int main(void) {
    int a[] = {29, 10, 14, 37, 13};
    int b[] = {29, 10, 14, 37, 13};
    int c[] = {29, 10, 14, 37, 13};
    int n = 5;

    bubble_sort(a, n);    printf("Bubble:    "); print_array(a, n);
    selection_sort(b, n); printf("Selection: "); print_array(b, n);
    insertion_sort(c, n); printf("Insertion: "); print_array(c, n);
    return 0;
}

Output

Bubble:    10 13 14 29 37 
Selection: 10 13 14 29 37 
Insertion: 10 13 14 29 37
  • Bubble sort compares neighbours and swaps them when they are out of order. After each pass the largest remaining value has “bubbled” to the end. The swapped flag stops early when a pass makes no swaps, so an already sorted array needs only one pass.
  • Selection sort finds the smallest value in the unsorted part and swaps it into the next position. It always makes about n²/2 comparisons but at most n − 1 swaps, which helps when writing to memory is expensive.
  • Insertion sort takes each value and slides it left into its place among the already sorted values, like sorting playing cards in your hand.

Tracing Insertion Sort

#include <stdio.h>

/* Insertion sort that prints the array after each step */
int main(void) {
    int a[] = {29, 10, 14, 37, 13};
    int n = 5;
    long comparisons = 0;

    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0) {
            comparisons++;
            if (a[j] <= key) break;
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
        printf("After inserting %2d: ", key);
        for (int k = 0; k < n; k++) printf("%d ", a[k]);
        printf("\n");
    }
    printf("Comparisons: %ld\n", comparisons);
    return 0;
}

Output

After inserting 10: 10 29 14 37 13 
After inserting 14: 10 14 29 37 13 
After inserting 37: 10 14 29 37 13 
After inserting 13: 10 13 14 29 37 
Comparisons: 8

After each step the left part of the array is sorted. Inserting 37 needs just one comparison because it is already larger than everything before it. That is why insertion sort is very fast on nearly sorted data: each element only moves a short distance.

Comparison

AlgorithmBestAverage / worstExtra spaceStable?
Bubble sortO(n)O(n²)O(1)Yes
Selection sortO(n²)O(n²)O(1)No
Insertion sortO(n)O(n²)O(1)Yes
  • In-place means the algorithm needs only a constant amount of extra memory; all three are in-place.
  • Stable means equal values keep their original order. That matters when you sort records, for example sorting students by marks while keeping alphabetical order among equal marks.
  • For large inputs, use an O(n log n) algorithm such as merge sort, quick sort or heap sort. Even so, insertion sort is used inside fast library sorts for small sub-arrays because it has very little overhead.

See Big O notation if the complexity notation is new to you.

Common Mistakes

  1. Off-by-one loop bounds, such as letting j + 1 run past the end of the array in bubble sort.
  2. Swapping without a temporary variable, which overwrites one of the values.
  3. Using < instead of <= in the wrong place, which can break stability.
  4. Choosing an O(n²) sort for large data; with 1,000,000 items it needs around a trillion steps.

Practice Exercises

Exercise 1. Change insertion sort to sort in descending order.

Show answer

Flip the comparison in the inner loop: while (j >= 0 && a[j] < key). Larger values now stay to the left.

Exercise 2. How many swaps does selection sort make on {5, 4, 3, 2, 1}?

Show answer

Two real swaps (5 with 1, then 4 with 2). After that the middle value 3 is already in place, although the simple code above still performs “swaps” of an element with itself.

Frequently Asked Questions

Which simple sort is the best?

Insertion sort is usually the best of the three: it is stable, in-place, and very fast on small or nearly sorted arrays. Bubble sort is mainly used for teaching.

What sort does C’s qsort use?

The C standard does not say. Most libraries use a quick sort variant or an introsort that switches to heap sort and insertion sort when needed, giving O(n log n) performance in practice.

Summary

  • Bubble sort swaps neighbours; selection sort picks the minimum; insertion sort shifts items into place.
  • All three are O(n²) on average and use O(1) extra memory.
  • Insertion sort is O(n) on nearly sorted data and is stable.
  • Use O(n log n) algorithms for large inputs.

Next: Merge Sort in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *