Docsity

Analysis of the Complexity of Insertion Sort Algorithm, Slides of Computer Science

Partial preview of the text

Download Analysis of the Complexity of Insertion Sort Algorithm and more Slides Computer Science in PDF only on Docsity!

Insertion Sort

for (int i = 1; i < a.length; i++) {// insert a[i] into a[0:i-1] int t = a[i]; int j; for (j = i - 1; j >= 0 && t < a[j]; j--) a[j + 1] = a[j]; a[j + 1] = t; }

Complexity

 Space/Memory

 Time

  • Count a particular operation
  • Count number of steps
  • Asymptotic complexity

Comparison Count

 Pick an instance characteristic … n, n =

a.length for insertion sort

 Determine count as a function of this

instance characteristic.

Comparison Count

for (j = i - 1; j >= 0 && t < a[j]; j--)

a[j + 1] = a[j];

How many comparisons are made?

Comparison Count

 Worst-case count = maximum count

 Best-case count = minimum count

 Average count

Worst-Case Comparison Count

for (j = i - 1; j >= 0 && t < a[j]; j--)

a[j + 1] = a[j];

a = [1, 2, 3, 4] and t = 0 => 4 compares

a = [1,2,3,…,i] and t = 0 => i compares

Step Count

A step is an amount of computing that

does not depend on the instance

characteristic n

10 adds, 100 subtracts, 1000 multiplies

can all be counted as a single step

n adds cannot be counted as 1 step

Step Count

for (int i = 1; i < a.length; i++) {// insert a[i] into a[0:i-1] int t = a[i]; int j; for (j = i - 1; j >= 0 && t < a[j]; j--) a[j + 1] = a[j]; a[j + 1] = t; } for (int i = 1; i < a.length; i++) 1 {// insert a[i] into a[0:i-1] 0 int t = a[i]; 1 int j; 0 for (j = i - 1; j >= 0 && t < a[j]; j--) 1 a[j + 1] = a[j]; 1 a[j + 1] = t; 1 } 0 s/e

Step Count

for (int i = 1; i < a.length; i++) {// insert a[i] into a[0:i-1] int t = a[i]; int j; for (j = i - 1; j >= 0 && t < a[j]; j--) a[j + 1] = a[j]; a[j + 1] = t; } for (int i = 1; i < a.length; i++) 1 {// insert a[i] into a[0:i-1] 0 int t = a[i]; 1 int j; 0 for (j = i - 1; j >= 0 && t < a[j]; j--) 1 a[j + 1] = a[j]; 1 a[j + 1] = t; 1 } 0 s/e steps

i

i+ 1

Step Count

for (int i = 1; i < a.length; i++) { 2i + 3} step count for for (int i = 1; i < a.length; i++) is n step count for body of for loop is 2(1+2+3+…+n-1) + 3(n-1) = (n-1)n + 3(n-1) = (n-1)(n+3)

Complexity of Insertion Sort

 Time or number of operations does not

exceed c.n

2

on any input of size n ( n

suitably large).

 Actually, the worst-case time is

Theta( n

2

) and the best-case is Theta( n )

 So, the worst-case time is expected to

quadruple each time n is doubled

Complexity of Insertion Sort

 Is O(n

2

) too much time?

 Is the algorithm practical?

Impractical Complexities

9

instructions/second

n n

4

n

10

n 1000 17min 3.2 x 10 13 years 3.2 x 10 283 years 10000 116 days ??? ??? 10 6 3 x 10 7 years ?????? ??????

Faster Computer Vs Better

Algorithm

Algorithmic improvement more useful

than hardware improvement.

E.g. 2

n

to n

3