Selection Sort
Main Idea
- Scan the array from the left to the right of the array;
- n iterations;
- in each iteration i (0 <= i <= n-1), find the index
min
of the smallest entry in the remaining part of the array - elements stored on the “right-hand-side”/aftera[i]
; - swap
a[i]
anda[min]
.
Invariants
- Elements from index
0
up to indexi
(in other words, to the left ofi
) are sorted; - No element from index
i
up to the last element is smaller than any element to the left ofi
(otherwise they would have been themin
element!).
Complexity
Insertion Sort
Main Idea
- Again, scan from left to right;
- n iterations;
- in each iteration i (0 <= i <= n-1), insert element
a[i]
into the correct position in the elements to its left, by continuously comparing and swapping between elements in the reverse order.
Invariants
- Elements from index
0
up to indexi
are sorted, However, the order is NOT the final order, as in each iteration, we have never cared about the elements to the right ofi
!