Add insertion sort notes.

pull/2/head
Joshua Potter 2024-02-02 18:22:08 -07:00
parent d744ce4ebc
commit 21517314a4
1 changed files with 18 additions and 1 deletions

View File

@ -15,7 +15,24 @@ tags:
| Worst Case ||
| Average Case ||
| Memory ||
| In place? ||
| In place ||
| Stable ||
Insertion sort works by advancing an index `i` through an array `A[1..n]` such that `A[1..i]` is put into sorted order. Consider precondition `Q` and postcondition `R`:
* `Q`: `i = 1`
* `R`: `i = n` and `A[1..n]` is in sorted order
Next establish loop invariant `P` and bounds function `t`:
* `P`: `1 \leq i \leq n` and `A[1..i]` is in sorted order
* `t`: the number of inversions of `A[1..i]`
## Analogy
Suppose you have a shuffled deck of playing cards face-down on a table. Start by grabbing a card from the deck with your left hand. For the remainder of the cards, use your right hand to transition the topmost card to the end of your left hand. If the newly placed card isn't in sorted order, move it one position closer to the start. Repeat until it's in sorted order.
If you repeat this process for every card in the deck, your left hand will eventually contain the entire deck in sorted order.
## References