It is convenient to operations or executed define the

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: depends on the problem The input depends – # items, # bits required, more than one input • The running time (complexity) of an algorithm on The running of a particular input iis the number of primitive s particular operations or “steps” executed. It is convenient to operations or executed. define the notion of step so that it is as machinemachine independent as possible NCKU IIM NCKU 資料結構 Chapter 2 資料結構 8 Running Time of Insertion-Sort of Insertion • INSERTION-SORT(array A) 1 for j=2 to length[A] 2 do key=A[j] 3 // Insert A[j] to the sorted sequence A[1..j-1]. 4 i=j-1 5 while i>0 and A[i]>key 6 do A[i+1]=A[i] 7 i=i-1 8 A[i+1]=key Cost c1 c2 0 c4 c5 c6 c7 c8 Best n n-1 n-1 n-1 n-1 0 0 n-1 Worst n n-1 n-1 n-1 ∑t ∑ (t − 1) ∑ (t − 1) n-1 n j =2 j n j =2 j n j =2 j • tj: the number of times tthe while loop test iin line 5 is executed for the he while n number value of j. NCKU IIM NCKU 資料結構 Chapter 2 資料結構 9 Complexity of Insertion-Sort Best case: Array A is already sorted in non-decreasing order: tj=1 T ( n ) = c1n + c 2 ( n − 1) + c 4 ( n − 1) + c5 ( n − 1) + c8 ( n − 1) = ( c1 + c 2 + c 4 + c5 + c8 ) n − ( c 2 + c 4 + c5 + c8 ) = Θ ( n ) Worst case: Array A is already sorted in non-increasing order: tj=j T ( n ) = c1n + c 2 ( n − 1) + c 4 ( n − 1) + c5 ∑ j = 2 t j + c6 ∑ j = 2 (t j − 1) + c7 ∑ j = 2 (t j − 1) n n n + c8 ( n − 1) c5 c 6 c 7 2 c c c + + ) n + ( c1 + c 2 + c 4 + 5 − 6 − 7 + c8 ) n − ( c 2 + c 4 + c5 + c8 ) 22 2 222 = Θ(n 2 ) =( • Best-case analysis may be...
View Full Document

This note was uploaded on 02/08/2013 for the course SCI 399 taught by Professor Bob during the Winter '12 term at Bismarck State College.

Ask a homework question - tutors are online