Insertion Sort: Analysis of Complexity: Georgy Gimel'farb
Insertion Sort: Analysis of Complexity: Georgy Gimel'farb
Georgy Gimel’farb
1 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
3 Analysis of inversions
2 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
n − 1 iterations (stages) i = 1, 2, . . . , n − 1;
j; 1 ≤ j ≤ i, comparisons and j or j − 1 moves per stage:
1 Initialisation: the head sublist of size 1.
2 Iteration: until the tail sublist is empty, repeat:
1 Choose the first element, x = a[i] in the tail sublist.
2 Find the last element, y = a[j]; 1 ≤ j ≤ i − 1, in the head
sublist not exceeding x.
3 Insert x after y in the head sublist.
The first element, a[i], of the tail is moved to the correct position
in the head by exhaustive backward search, comparing it to each
element, a[i − 1], . . ., of the head until finding the right place.
The best case, Θ(n): if the inputs A are already in sorted order:
a[0] < a[1] < . . . < a[n − 1], i.e. A = {1, 2, 3, 4}.
• One comparison and no moves per stage i; i = 1, . . . , n − 1.
• Comparisons in total: 1 + 1 + . . . + 1 = n − 1 ∈ Θ(n).
The worst case, Θ(n2 ): if the inputs A contain distinct items in
reverse order: a[0] > a[1] > . . . > a[n − 1], i.e. A = {4, 3, 2, 1}
• i comparisons and i moves per stage i; i = 1, . . . , n − 1.
• Comparisons in total:
2
1 + 2 + . . . + n − 1 = (n−1)n
2 = n 2−n ∈ Θ(n2 ).
4 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
5 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
i(i+1)
1 + 2 + ... + i + i 2+i i i i 1
Ci = = = + ≡ + 1−
i+1 i+1 2 i+1 2 i+1
6 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
C1 C2 C n−1
z
}| { z }| { z
}|
{
1 1 2 1 n−1 1
C = + 1− + + 1− +... + + 1−
2 2 2 3 2 n
1
= 2 (1 + 2 + . . . + (n − 1)) +
| {z }
(n−1)n
2
1 1 1
1− + 1− + ... + 1 −
2 3 n
| {z }
(n−1)−(Hn −1)=n−Hn
(n−1)n
= 4 + n − Hn ∈ Θ(n2 )
n
1
P
where Hn = i ≈ ln n when n → ∞ is the n-th harmonic number.
i=1
7 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
1 Rn dx
Hn > x = ln n > Hn − 1
1
0.5
0.25
0 1 2 3 4 5 6 7 8 9 10
8 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
Analysis of Inversions
The number of inversions measures how far a list is from being sorted.
9 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
Analysis of Inversions
n−1
P
Because Ii = Mi is always true, the total number I = Ii of
i=1
n−1
P
inversions is equal to the total number M = Mi of backward
i=1
moves of elements a[i] during the sort.
10 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
Analysis of Inversions
n−1
P
The total number of data comparisions C = Ci is also equal to
i=1
the total number of inversions plus at most n − 1.
12 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts
13 / 15
Outline Worst-case Average-case Inversions More Θ(n2 ) sorts