Sorting arranges a list into ascending or descending order. Sorted data is easier to read and lets binary search work. A common method taught at this level is bubble sort.
How bubble sort works
Bubble sort compares each pair of adjacent items. If they are in the wrong order, it swaps them. It repeats this along the list, pass after pass, until no more swaps are needed. Large values "bubble" toward the end, one position per pass. Because it only ever looks at neighbours, bubble sort is easy to trace by hand, which is why it is taught first even though faster methods exist for very long lists.
Ascending and descending order
You can sort into ascending order (smallest to largest) or descending order (largest to smallest). The only change is the comparison: for ascending you swap when the left item is bigger; for descending you swap when the left item is smaller.
Key idea
Bubble sort compares ADJACENT pairs and swaps if they are out of order. After each full pass, the next largest value is in its final place. The list is sorted when a pass makes no swaps.
Example
Sort 5 3 8 1 ascending. Pass 1: compare 5 and 3 → swap to 3 5 8 1; 5 and 8 → no swap; 8 and 1 → swap to 3 5 1 8. The 8 is now last. Pass 2: 3 and 5 no swap; 5 and 1 swap → 3 1 5 8. Pass 3: 3 and 1 swap → 1 3 5 8. The list is now sorted.
Remember
- Bubble sort only ever compares neighbouring items.
- A swap happens only when a pair is in the wrong order.
- The largest unsorted value moves to the end after each pass.
- Sorting is often needed before a binary search.