Class 1: Introduction

 

 

INSERTION-SORT (A, n)

1     for j=2 to n

2           key=A[j]

3           // insert A[j] into sorted A[1..j-1]

4           i=j-1

5           while i>0 and A[i]>key

6                 A[i+1] = A[i]

7                 i = i-1

8           A[i+1] = key

 

 

INSERTION-SORT (A, n)                   cost      times

1     for j=2 to n                      c1      n

2           key=A[j]                      c2      n-1

3           // insert A[j] into sorted A[1..j-1]

4           i=j-1                         c4      n-1

5           while i>0 and A[i]>key          c5      Sj=2..n tj

6                 A[i+1] = A[i]            c6      Sj=2..n (tj-1)

7                 i = i-1                 c7      Sj=2..n (tj-1)

8           A[i+1] = key             c8      n-1

Total cost T(n) is:

 

T(n) = c1*n +c2*(n-1) + c4*(n-1) + c5*Sj=2..n tj + c6*Sj=2..n(tj-1) + c7*Sj=2..n(tj-1) + c8(n-1)

 

The best case occurs when the array is already sorted:

 

T(n) =  c1*n +c2*(n-1) + c4*(n-1) + c8(n-1) = (c1+c2+c4+c5+c8)n – (c2+c4+c5+c8)

 

The running time can be expressed as an+b, i.e. a linear function of n.

 

If the array is in reverse order – the worst case results. In this case tj = j, which means

 

Sj=2..n tj = n(n+1)/2 -1

Sj=2..n (tj-1) = n(n-1)/2

 

T(n) = (c5/2+c6/2+c7/2)n2 + (c1+c2+c4+c5/2-c6/2-c7/2+c8)n – (c2+c4+c5+c8)

 

The worst-case running time can be expressed as an^2+bn+c; it is thus a quadratic function of n.