Kodewick
Start learning →
Bubble sort and selection sort39 / 50

Bubble sort and selection sort

Lesson 39 of 50 · Part 8 · Sorting · about 20 minutes

Bubble sort compares neighbours and swaps the bigger one back, while selection sort picks the smallest each pass and swaps it to the front; both make n(n − 1)/2 comparisons, O(n²), and only bubble sort is stable.

The most direct way to sort n numbers: each pass puts one number where it belongs, and n − 1 passes later it's sorted. Bubble sort and selection sort both do this; they differ in how a pass finds that number and how it gets it there.

Bubble sort: compare neighbours, swap the bigger back

From the start, compare each pair of neighbours and swap when the first is bigger. After one pass the largest has "bubbled" to the end, and the next pass can leave the last one alone.

acomparisons 0 · swaps 05149201234
1for (int i = 0; i < n - 1; i++)2    for (int j = 0; j < n - 1 - i; j++)3        if (a[j] > a[j + 1])4            swap(&a[j], &a[j + 1]);

Bubble sort's first pass: comparing all the way along, the largest, 9, is swapped to the end

You can run the whole program step by step: the array is drawn as bars, and the two being swapped slide past each other.

main.c
1#include <stdio.h>2 3void swap(int *x, int *y) {4    int t = *x;5    *x = *y;6    *y = t;7}8 9int main(void) {10    int a[] = {5, 1, 4, 9, 2};11    int n = 5;12    for (int i = 0; i < n - 1; i++)13        for (int j = 0; j < n - 1 - i; j++)14            if (a[j] > a[j + 1])15                swap(&a[j], &a[j + 1]);16    for (int i = 0; i < n; i++)17        printf("%d ", a[i]);18    printf("\n");19    return 0;20}
Output
1 2 4 5 9 
Choose one

Bubble sort 3 6 2 5 1 (smallest first). What does the array look like after pass 1?

Choose one

Now pass 2. What does 3 6 2 5 1 become?

Fill inTap one to fill a blank; tap a blank to take it back

Bubble sort swaps two neighbours. Fill in the number so the program sorts 3 6 2 5 1.

1#include <stdio.h>2 3void swap(int *x, int *y) {4    int t = *x;5    *x = *y;6    *y = t;7}8 9int main(void) {10    int a[] = {3, 6, 2, 5, 1};11    int n = 5;12    for (int i = 0; i < n - 1; i++)13        for (int j = 0; j < n - 1 - i; j++)14            if (a[j] > a[j + 1])15                swap(&a[j], &a[j + ]);16    for (int i = 0; i < n; i++)17        printf("%d ", a[i]);18    printf("\n");19    return 0;20}

Stop early when it's sorted

If a pass makes no swap at all, the array is sorted and the remaining passes can be skipped. Add a swapped flag:

1for (int i = 0; i < n - 1; i++) {2    int swapped = 0;3    for (int j = 0; j < n - 1 - i; j++)4        if (a[j] > a[j + 1]) {5            swap(&a[j], &a[j + 1]);6            swapped = 1;7        }8    if (!swapped) break;    // no swap this pass: sorted9}

On an already sorted array it then takes one pass of n − 1 comparisons: the best case is O(n).

Guess the outputA wrong guess is fine

1 2 3 5 4 has just one pair out of order. With the early stop, how many passes does it take?

1#include <stdio.h>2 3int main(void) {4    int a[] = {1, 2, 3, 5, 4};5    int n = 5, rounds = 0;6    for (int i = 0; i < n - 1; i++) {7        int swapped = 0;8        rounds++;9        for (int j = 0; j < n - 1 - i; j++)10            if (a[j] > a[j + 1]) {11                int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;12                swapped = 1;13            }14        if (!swapped) break;15    }16    printf("%d\n", rounds);17    return 0;18}
Choose one

Which input is slowest for bubble sort with the early stop?

Exercise 1

Bubble sort with an early stop

Finish the sort, and count how many swaps it makes.

It should print
1 2 3 6 7 8
7
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int a[] = {3, 7, 1, 8, 2, 6};5    int n = 6, swaps = 0;6    // bubble sort: compare neighbours, swap when the first is bigger (swaps++); break after a pass with no swap7    for (int i = 0; i < n; i++)8        printf("%d ", a[i]);9    printf("\n%d\n", swaps);10    return 0;11}
Output
Press Run or Ctrl+Enter

Selection sort: pick the smallest each pass

Selection sort goes about it differently: pass i finds the smallest of a[i] to the end and swaps it with a[i]. One swap per pass.

acomparisons 0 · swaps 05149201234
1for (int i = 0; i < n - 1; i++) {2    int min = i;3    for (int j = i + 1; j < n; j++)4        if (a[j] < a[min]) min = j;5    swap(&a[i], &a[min]);6}

Selection sort's first pass: min holds the index of the smallest so far, and only at the end is it swapped to the front
main.c
1#include <stdio.h>2 3int main(void) {4    int a[] = {5, 1, 4, 9, 2};5    int n = 5;6    for (int i = 0; i < n - 1; i++) {7        int min = i;8        for (int j = i + 1; j < n; j++)9            if (a[j] < a[min])10                min = j;11        int t = a[i];12        a[i] = a[min];13        a[min] = t;14    }15    for (int i = 0; i < n; i++)16        printf("%d ", a[i]);17    printf("\n");18    return 0;19}
Output
1 2 4 5 9 
Choose one

Selection sort 5 1 4 9 2. What does the array look like after pass 2?

Fill inTap one to fill a blank; tap a blank to take it back

What do you remember when you find a smaller number? Fill in the blank so selection sort sorts 5 1 4 9 2.

1#include <stdio.h>2 3int main(void) {4    int a[] = {5, 1, 4, 9, 2};5    int n = 5;6    for (int i = 0; i < n - 1; i++) {7        int min = i;8        for (int j = i + 1; j < n; j++)9            if (a[j] < a[min])10                min = ;11        int t = a[i];12        a[i] = a[min];13        a[min] = t;14    }15    for (int i = 0; i < n; i++)16        printf("%d ", a[i]);17    printf("\n");18    return 0;19}
Exercise 2

Selection sort, largest first

Sort from largest to smallest: each pass picks the largest and puts it in front.

It should print
9 7 5 4 2
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int a[] = {4, 9, 2, 7, 5};5    int n = 5;6    for (int i = 0; i < n - 1; i++) {7        int max = i;8        // find the index of the largest in a[i+1..n-1], then swap it with a[i]9    }10    for (int i = 0; i < n; i++)11        printf("%d ", a[i]);12    printf("\n");13    return 0;14}
Output
Press Run or Ctrl+Enter

How many comparisons and swaps

Both are two nested loops with the same comparisons: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2, O(n²). They differ in swaps:

ComparisonsSwaps (worst)Best caseStable?
Bubble (with early stop)n(n − 1)/2n(n − 1)/2O(n), already sortedstable
Selectionn(n − 1)/2n − 1O(n²), it always compares everythingunstable

Stable means two equal values keep their order after sorting. Bubble sort only swaps neighbours, never equal ones, so it's stable; selection sort can swap a value a long way, as in 2a 2b 1: the first pass swaps 1 with 2a, giving 1 2b 2a, and the two 2s are reversed. Stability matters when sorting by several keys (by score, then by ID).

In exams: sorts where each pass fixes one element's final place: bubble (the largest), selection (the smallest), heap sort; fewest swaps: selection sort, at most n − 1.

Choose one

5a 8 5b 2 has two 5s (a and b only tell them apart). What does selection sort make of it after pass 1?

Choose one

How many comparisons does selection sort make on 6 numbers?

Change it

Each person has a score and a name, bubble-sorted by score from low to high. As written, it swaps people with the same score too. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).

1#include <stdio.h>2 3typedef struct {4    int score;5    char name;6} Item;7 8int main(void) {9    Item a[] = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};10    int n = 4;11    for (int i = 0; i < n - 1; i++)12        for (int j = 0; j < n - 1 - i; j++)13            if (a[j].score  a[j + 1].score) {14                Item t = a[j];15                a[j] = a[j + 1];16                a[j + 1] = t;17            }18    for (int i = 0; i < n; i++)19        printf("%d%c ", a[i].score, a[i].name);20    printf("\n");21    return 0;22}
Should print
1B 1D 2A 2C

Summary

Take-away

Bubble and selection: one number placed per pass, both O(n²)

  • Bubble: compare neighbours, the bigger moves back; stop after a pass with no swap, best O(n)
  • Selection: find the smallest's index each pass, one swap, at most n − 1 swaps
  • Both make n(n − 1)/2 comparisons; bubble is stable, selection is not
1for (i = 0; i < n - 1; i++)2    for (j = 0; j < n - 1 - i; j++)3        if (a[j] > a[j + 1]) swap(&a[j], &a[j + 1]);