Week 3 Slide 2 Insertion Sort
Week 3 Slide 2 Insertion Sort
38 45
60 60
66 45
66 79 47 13 74 36 21 94 22 57 16 29 81
10
12
Insertion Sort
11
6 10 24 36
12
Insertion Sort
12
6 10 24 3
6
12
13 Insertion Sort
input array
5 2 4 6 1
3
at each iteration, the array is divided in two sub-arrays:
sorted unsorted
14 Insertion Sort
15
Alg.: INSERTION-SORT(A) 1 2 3 4 5 6 7 8
for j ← 2 to n a1 a2 a3 a4 a5 a6 a7 a8
do key ← A[ j ]
key
Insert A[ j ] into the sorted sequence A[1 . . j -1]
i←j-1
while i > 0 and A[i] > key
do A[i + 1] ← A[i]
i←i–1
A[i + 1] ← key
Insertion sort – sorts the elements in place
16
Alg.: INSERTION-SORT(A)
for j ← 2 to n
do key ← A[ j ]
Insert A[ j ] into the sorted sequence A[1 . . j -1]
i←j-1
while i > 0 and A[i] > key
do A[i + 1] ← A[i]
i←i–1
A[i + 1] ← key
Invariant: at the start of the for loop the elements in A[1 . . j-1]
are in sorted order
Proving Loop Invariants
17
j-1 j
Invariant: at the start of the for loop the elements in A[1 . . j-1]
are in sorted order
Analysis of Insertion Sort
21
INSERTION-SORT(A) cost
times
for j ← 2 to n
c1 n
do key ← A[ j ]
Insert A[ j ] into the sorted sequence A[1c.2 . j -1] n-
1
i←j-1
0
n
n-t
while i > 0 and A[i] > key j 2 j
1
n
(t j 1)
do A[i + 1] ← A[i] j 2
c4 n-(t 1)
n
i←i–1 1
j 2 j
A[i + 1] ← key c5
tj: # of times the while statement is executed at iteration j
n n c6
n
T (n) c1n c2 (n 1) c4 (n 1) c5 t j c6 t j 1 c7 t j 1 c8 (n 1)
j 2 j 2 c7
j 2
Best Case Analysis
22
The array is already sorted
“while i > 0 and A[i] > key”
A[i] ≤ key upon the first time the while loop test is run (when i = j -1)
tj = 1
+ c5 + c8)
= an + b = O(n)
n n n
T (n) c1n c2 (n 1) c4 (n 1) c5 t j c6 t j 1 c7 t j 1 c8 (n 1)
j 2 j 2 j 2
Worst Case Analysis
n( n 1) n( n 1) n( n 1)
T ( n ) c1n c2 ( n 1) c4 ( n 1) c5 1 c6 c7 c8 ( n 1)
2 2 2
an 2 bn c
a quadratic function of n
n n n
T (n) T(n) (n 12)) c4 (n 1) c5 order
c1n =c2 O(n t j c6 oft jgrowth
1 c7 int jn 21 c8 (n 1)
j 2 j 2 j 2
23
Comparisons and Exchanges in Insertion Sort
24
INSERTION-SORT(A)
cost
for j ← 2 to n
times
do key ← A[ j ] c1 n
Insert A[ j ] into the sorted sequence
c2 n-
A[1 . . j -1]
n2/2 comparisons 1
i←j-1
n-t
n
0 j 2 j
Advantages
Good running time for “almost sorted” arrays O(n)
Disadvantages
O(n2) running time in worst and average case
n2/2 comparisons and exchanges