Sorting Flashcards
Total order
A binary relation ≤ that satisfies:
- Antisymmetry: if v ≤ w and w ≤ v, then v=w.
- Transitivity: if v ≤ w and w ≤ x, then v ≤ x.
- Totality: either v ≤ w or w ≤ v or both
Selection sort
- In iteration
i
, find indexmin
of smallest remaining entry. - Swap
a[i]
anda[min]
.
Insertion sort
In iteration i
, swap a[i]
with each larger entry to its left.
Analysis: Selection sort
Selection sort uses (N - 1) + (N - 2) + ... + 1 + 0 ~ N²/2
compares and N
exchanges.
Running time is insensitive to input. Quadratic time, even if input is sorted.
Data movement is minimal.
Insertion sort: Best & worst case
If the array is in ascending order, insertion sort makes N-1 compares and 0 exchanges.
If the array is in descending order (and no duplicates), insertion sort makes ~ ½ N ²
compares and ~ ½ N ²
exchanges.
Knuth shuffle
In iteration i
, pick integer r
between 0
and i
uniformly at random.
Swap a[i]
and a[r]
.
Convex hull
The convex hull of a set of N points is the smallest perimeter fence enclosing the points.
Basic plan
Mergesort
- Divide array into two halves
- Recursively sort each half
- Merge the two halves