This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Lecture 4 Divide and Conquer for Nearest Neighbor Problem ShangHua Teng MergeSort( A,p,r ) A procedure sorts the elements in the subarray A [ p..r ] using divide and conquer • MergeSort( A,p,r ) – if p >= r , do nothing – if p< r then • MergeSort( A,p,q ) • MergeSort( A,q+1,r ) • Merge( A,p,q,r ) • Starting by calling MergeSort( A,1,n ) 2 / ) ( r p q + ← A = MergeArray( L,R ) Assume L [ 1:s ] and R[ 1:t ] are two sorted arrays of elements: MergeArray( L,R ) forms a single sorted array A [ 1:s+t ] of all elements in L and R . • A = MergeArray( L,R ) – – – for k 1 to s + t • do if – then – else 1 ]; [ ] [ + ← ← i i i L k A 1 ]; [ ] [ + ← ← j j j R k A ∞ ← + ∞ ← + ] 1 [ ; ] 1 [ t R s L ] [ ] [ j R i L ≤ 1 ; 1 ← ← j i Complexity of MergeArray • At each iteration, we perform 1 comparison, 1 assignment (copy one element to A ) and 2 increments (to k and i or j ) • So number of operations per iteration is 4. • Thus, MergeArray takes at most 4(s+t) time. • Linear in the size of the input . Merge ( A,p,q,r ) Assume A [ p..q ] and A[ q+1..r ] are two sorted Merge( A,p,q,r ) forms a single sorted array A [ p..r ]. • Merge (A,p,q,r) – – – – ∞ ← + ∞ ← + ] 1 [ ; ] 1 [ t R s L ; ; 1 q r t p q s ← + ← ] , 1 [ ]; .. [ r q A R q p A L + ← ← ) , ( ] .. [ R L MergeArray r p A ← MergeSort( A,p,r ) A procedure sorts the elements in the subarray A [ p..r ] using divide and conquer...
View
Full
Document
This note was uploaded on 03/08/2010 for the course CS 232 taught by Professor Bera during the Spring '09 term at BU.
 Spring '09
 BERA
 Algorithms, Sort

Click to edit the document details