Lesson 14: Sorting an array — bubble sort
We have an array — now we'll learn to order it from smallest to largest. The idea of bubble sort is simple: compare each pair of neighbors, and if they're in the wrong order — swap them. Swapping needs a helper variable in three steps: temp = a; a = b; b = temp; — without temp the first value is era
Imagine kids in a line arranging themselves by height: each time two neighbors compare, and if the left one is taller — they swap. After one pass along the line, the tallest kid has already 'bubbled' to the end — like a bubble rising to the top.
- sorting
- Arranging array elements in order, e.g. from smallest to largest. A sorted array is easy to search and read.
- bubble sort
- A sort that repeatedly compares neighbors and swaps them; each pass the largest 'bubbles' to the end.
- swap with temp
- Three steps: temp = a; a = b; b = temp; — the temp variable saves the value about to be overwritten.
- pass
- One run of the inner loop along the array. After pass i, the end of the array is already sorted.
- selection sort
- A different idea: each round find the smallest remaining element and place it in position — one swap per round.