Searching and Sorting
Finding values quickly and putting data in order, from linear search to merge sort, quick sort and radix sort.
Searching
Find a value by scanning, or by halving a sorted range again and again.
- Linear search Linear search checks each element from left to right until it finds the target. It works on any array and takes O(n) time.
- Binary search Find a value in a sorted array by looking at the middle and throwing away the half that cannot contain it, until one look remains.
Elementary sorting
Simple quadratic sorts that show how comparisons and swaps put data in order.
- Bubble sort Bubble sort compares neighbours and swaps them when out of order, so the largest values bubble to the end. The sorted suffix grows by one…
- Selection sort Selection sort scans for the smallest remaining value and swaps it into place, one swap per pass. It always takes O(n²) comparisons.
- Insertion sort Insertion sort lifts each element out and slides it left into the sorted prefix. It is fast on nearly sorted data.
Efficient sorting
Sorts that reach n log n or better, how to compare them and how real libraries sort.
- Merge sort Merge sort splits the array in half, sorts each half recursively and merges the sorted halves. It always takes O(n log n) time and is…
- Quick sort: partitioning and pivots Quick sort picks a pivot, partitions smaller values left and larger right, then recurses on both sides. It is fast in practice but O(n²)…
- Counting sort Counting sort counts how often each key appears, turns the counts into positions with prefix sums, and places items stably. No comparisons…