# R 2 n2 r q 3 create arrays l1 n11 and r1 n21 4

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: r: merge sort – • recursive: recursive: • divide div • conquer conquer • combine (merge) key procedure key MERGE-SORT (A[1..n]) 1. If n=1, done! If n=1 2. Recursively sort 2 llists: A[ 1.. ⎢ n / 2 ⎥ ] and A[ ⎢ n / 2⎥ + 1..n] ists: A[ ⎣ ⎦ and A[ ⎣ Recursively ⎦ 3. Merge the 2 sorted lists the NCKU IIM NCKU 資料結構 Chapter 2 資料結構 Merge Sort Algorithm Merge MERGE(A, p, q, r) p <= q <r; A[p..q] and A[q+1..r] are in sorted order; 1 n1 = q – p + 1 merges them to a single sorted A[p..r] 2 n2 = r – q 3 // create arrays L[1.. n1+1] and R[1.. n2+1] 4 for i=1 to n1 for MERGE-SORT(A,p,r) 5 do L[i]=A[p+i – 1] do L[i]=A[p+i 1 if p<r 6 for j=1 to n2 for 2 then q=floor((p+r)/2) 7 do R[j]=A[q+j] do 3 MERGE-SORT(A, p, q) 8 L[n1+1] = ∞ +1] 4 MERGE-SORT(A, q+1, r) 9 R[n2+1] = ∞ +1] 5 MERGE (A, p, q, r) 10 i=1 11 j=1 MERGE-SORT(A,1,length[A]) gives the order 12 for k=p to r 12 for k=p n =1 ⎧ Θ(1) 13 do if L[i] <= R[j] do T ( n) = ⎨ 14 then A[k] = L[i] 14 th A[k] L[i ⎩2T (n / 2) + Θ(n) n > 1 15 i=i+1 16 else A[k] = R[j] 16 R[j ⇒ T (n) = Θ(n lg n) 17 j=j+1 18 Analyze Divide-and-Conquer Algorithms • Analyzing divide-and-conquer algorithms if n ≤ c Θ(1) ⎧ T ( n) = ⎨ ⎩aT (n / b) + D(n) + C (n) otherwise a subproblems, each has size 1/b of the original problem, each 1/b of D(n) time to divide, C(n) time to combine D(n) time C(n) See Chapter 4 • Analysis of merge sort Analysis Θ(1 ) if ⎧ T( n ) = ⎨ ⎩2T ( n / 2 ) + Θ( n ) if n =1 n >1 NCKU IIM NCKU 資料結構 Chapter 2 資料結構 19 Analysis of Merge Sort Let constant c represents the time require to solve problems Let represents of size 1 as well as the time per array element of the of as divide and combine steps. divide c if n = 1 ⎧ T ( n) = ⎨ ⎩2T (n / 2) + cn if n > 1 T ( n ) = Θ( n log n ) NCKU IIM NCKU 資料結構 Chapter 2 資料結構 Recursion Tree for Merge Sort Merge level nodes/ cost/ llevel evel level level cn 0 20 = 1 1 21 = 2 cn 2 22 = 4 cn . . . . . . cn N-1 2N-1=n Since 2N-1 = n, lg(2N-1) = lg(n) Since lg(2 lg(n llevels = N = 1+lg(n) evels 1+lg(n) T(n) = total cost = T(n) (levels)*(cost/level) (levels)*(cost/level) T(n) = cn [1+lg(n)] = O( n lg(n) ) T(n) cn n nodes at level N-1 • Each level takes cn time Each cn • Totally lg n + 1 levels Totally lg • Thus total time = cn(lg n + 1) cn(lg • Ignoring coefficient and Ignoring only keep dominating terms, we got Θ( n lg n) term • Asymptotically better Asymptotically than insertion sort • In practice, merge sort In beats insertion sort for n>30 or so n>30...
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