Lesson contents

Bubble sort

Compare neighbouring items. Swap neighbours that are out of order. After one full pass a largest item has reached the end.

Simple example

Swap 3 with 2 and then 3 with 1. The next pass swaps 2 with 1. Print the sorted values.

Start3 2 1
Result1 2 3
main.rs
fn main() {
    let mut values: [i64; 3] = [3, 2, 1];
    let mut limit: i64 = 2;
    while limit > 0 {
        let mut i: i64 = 0;
        let mut swapped: i64 = 0;
        while i < limit {
            if values[(i) as usize] > values[((i + 1)) as usize] {
                let saved: i64 = values[(i) as usize];
                values[(i) as usize] = values[((i + 1)) as usize];
                values[((i + 1)) as usize] = saved;
                swapped = 1;
            }
            i += 1;
        }
        if swapped == 0 {
            break;
        }
        limit -= 1;
    }
    let mut i: i64 = 0;
    while i < 3 {
        println!("{}", values[(i) as usize]);
        i += 1;
    }
}
Output
1
2
3
Advertisements

Everyday examples

Reorder a line by height

Three pupils stand in order 150, 140, 130 centimetres. Where is 150 after one left-to-right pass?

Start150 140 130
Result140 130 150

The tallest pupil trades places twice and reaches the right end.

Keep tied receipts in order

Two receipts total 8 each. Should they exchange places when sorting by amount?

Start8A 8B
Result8A 8B

Swap only when the left amount is greater. Equal receipts keep their arrival order.

Recognise an ordered row

A shelf already holds parcels weighing 1, 2 and 4 kilograms. How many swaps occur?

Start1 2 4
Result0

Both comparisons are already in order. One pass confirms that the shelf is sorted.

Cost and limits

A swap-free pass lets the algorithm stop early. Reverse order takes O(n²) comparisons.