Data Structures & Algorithms

Table of Contents

Insertion sort

like sorting a hand of cards sequence is a sorted part followed by an unsorted part

algorithm:

pseudocode:

pseudocode

analysis:

linedescriptionconstant
1nothing
2n operationsconstant1 n
3n-1 operationsconstant2 (n-1)
4n-1 operationsconstant3 (n-1)
5worst case if A[i] > key always true
for fixed j we do the test j times:
$\sum_{j=2}^{n}=\frac{n(n+1)}{2}-1$
$\text{constant}_4(\frac{1}{2}(n(n+1))-1)$
6same, j-1 times assignment$\text{constant}_5(\frac{1}{2}(n-1)n)$
7same, j-1 times assignment$\text{constant}_6(\frac{1}{2}(n-1)n)$
8n-1 operations$\text{constant}_7 (n-1)$

sum all the constants, results in T(n) of form $an^2+bn+c$.

We have an² ≤ T(n), so T is in ϴ(n²). therefore the algorithm is quadratic time complexity.