



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




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; }
s Space/Memory s Time
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; }
s Pick an instance characteristic … n, n = a.length for insertion sort s Determine count as a function of this instance characteristic.
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
How many comparisons are made?
for (j = i - 1; j >= 0 && t < a[j]; j--) a[j + 1] = a[j];
number of compares depends on a[]s and t as well as on i
¾ Worst-case count = maximum count
¾ Best-case count = minimum count
¾ Average 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
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
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)
s O(n^2 )
s What does this mean?
s Time or number of operations does not exceed c.n^2 on any input of size n ( n suitably large). s Actually, the worst-case time is Theta( n^2 ) and the best-case is Theta( n ) s So, the worst-case time is expected to quadruple each time n is doubled
s Is O(n^2 ) too much time?
s Is the algorithm practical?
109 instructions/second n n nlogn n^2 n^3
1000 1mic 10mic 1milli 1sec
10000 10mic 130mic 100milli 17min
106 1milli 20milli 17min 32years
109 instructions/second n n^4 n^10 2 n
1000 17min 3.2 x 10^13 years
3.2 x 10^283 years (^10000) 116 days
??? ???
106 3 x 10^7 years
?????? ??????
Algorithmic improvement more useful than hardware improvement.
E.g. 2n^ to n^3