6.2. Sorting: Quadratic Sorts¶
6.2.1. Quadratic Sorts¶
6.2.1.1. Sorting¶
- Each record contains a field called the key.
Linear order: comparison.
- Measures of cost:
Comparisons
Swaps
6.2.1.2. Insertion Sort¶
What would you do if you have a stack of phone bills from the past two years and you want to order by date? A fairly natural way to handle this is to look at the first two bills and put them in order. Then take the third bill and put it into the right position with respect to the first two, and so on.
6.2.1.3. Initial Step¶
6.2.1.4. Analysis: Worst Case¶
6.2.1.5. Analysis: Best Case¶
6.2.1.6. Analysis: Average Case¶
6.2.1.7. Bubble Sort¶
1 / 13 Settings<<<>>>Moving from left to right, compare adjacent elements and swap if the left one is bigger than the right one.
- 200
- 101
- 152
- 543
- 554
- 115
- 786
- 147
6.2.1.8. Analysis¶
6.2.1.9. Selection Sort¶
1 / 15 Settings<<<>>>Moving from left to right, find the element with the greatest value.
- 200
- 101
- 152
- 543
- 554
- 115
- 786
- 147
6.2.1.10. Analysis¶
6.2.1.11. Summary¶
InsertionBubbleSelectionComparisons:Best CaseΘ(n)Θ(n2)Θ(n2)Average CaseΘ(n2)Θ(n2)Θ(n2)Worst CaseΘ(n2)Θ(n2)Θ(n2)Swaps:Best Case00Θ(n)Average CaseΘ(n2)Θ(n2)Θ(n)Worst CaseΘ(n2)Θ(n2)Θ(n)
6.2.1.12. Code Tuning (1)¶
General strategy: Test to avoid workBalance test cost, success probability, work saved“Optimizations” for quadratic sorts:Insertion Sort shift vs swaps: WorksSelection Sort viewed as an optimization of Bubble Sort: WorksSelection Sort avoid self-swaps: Does not workBubble Sort “i” vs “1”: WorksBubble Sort count comparisons/avoid unnecessary iterations: Does not workBubble Sort O(n) best case claim: Bogus