100 likes | 257 Views
CS1010 Discussion. Week 11 Aaron Tan. Insertion Sort (1/8). In a card game, we don’t normally sort our cards using Bubble Sort or Selection sort. (Just imagine that!) The closer algorithm we use is perhaps Insertion Sort .
E N D
CS1010 Discussion Week 11 Aaron Tan
Insertion Sort (1/8) • In a card game, we don’t normally sort our cards using Bubble Sort or Selection sort. (Just imagine that!) • The closer algorithm we use is perhaps Insertion Sort. • The Selection Sort, Bubble Sort and Insertion Sort belong to the exchange sort paradigm, and they are the three basic sorting techniques.
Insertion Sort (2/8) • Algorithm: Given an array v, on pass i, Insert v[i] into the correct position in the sorted region to its left, i.e. v[0] … v[i-1] • Example: pass 1 (assume n = 5) • Compare v[1] with v[0] • If v[1] < v[0], move v[1] to the front of v[0] (shifting needed) • The sorted region now consists of two elements: v[0] and v[1].
Sorted region 0 1 2 3 4 v 10 5 7 1 6 v 5 10 7 1 6 Sorted region Insertion Sort (3/8) • Pass 1: Where to insert v[1] in the sorted region to its left?
Sorted region 0 1 2 3 4 v 5 10 7 1 6 v 5 7 10 1 6 Sorted region Insertion Sort (4/8) • Pass 2: Where to insert v[2] in the sorted region to its left?
Sorted region 0 1 2 3 4 v 5 7 10 1 6 v 1 5 7 10 6 Sorted region Insertion Sort (5/8) • Pass 3: Where to insert v[3] in the sorted region to its left?
Sorted region 0 1 2 3 4 v 1 5 7 10 6 v 1 5 6 7 10 Sorted region Insertion Sort (6/8) • Pass 4 (final pass): Where to insert v[4] in the sorted region to its left? Sort completed. • An array of n elements requires n – 1 passes in Insertion Sort.
Sorted region 0 1 2 3 4 v 5 5 1 5 7 5 7 1 7 10 7 1 10 1 10 10 6 6 6 6 Insertion Sort (7/8) • In inserting v[i] to the front, we do not perform swapping to move v[i] to the right position. This is too inefficient. • For example, for pass 3, we don’t do this: This requires 3 swaps. Each swap requires 3 assignment statements. Hence, a total of 9 assignment statements. v[3] < v[2], swap them: v[2] < v[1], swap them: v[1] < v[0], swap them: v v v Sorted region
Sorted region 0 1 2 3 4 v 5 5 1 5 5 7 5 7 7 5 10 10 7 7 7 10 1 10 10 10 6 6 6 6 6 Insertion Sort (8/8) • Instead, we shift the elements in sorted region to make room for the insertion of v[i]. • For example, for pass 3, we do this: This requires 5 assignment statements only. Save v[3] in temp temp 1 temp < v[2], ‘shift’ v[2] one position right: Finally, copy temp to v[0] (where the shifting stops): temp < v[1], ‘shift’ v[1] one position right: temp < v[0], ‘shift’ v[0] one position right: v v v v Sorted region