This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 2 ) and another should have complexity O (min( N 1 ; N 2 )log (max( N 1 ; N 2 )) : Which (if any) is faster? (There are three possibilities here, rst algorithm is faster for all N 1 ; N 2 ; second algorithm is faster for all N 1 ; N 2 ; or the answer depends on the values of N 1 N 2 : ) Justify your answer. 1 Algorithm 1: Intersection(L1,L2) { int T1=1,T2=1; while ((T1<=N1) && (T2<=N2)) { if (L1[T1]<L2[T2]) T1++; else if (L1[T1]==L2[T2]) { printf(L1[T1]); T1++; T2++; } else T2++; } } Every iteration of the while loop moves by one array element(in L1 or L2 or both). As there are a total of N 1 + N 2 elements in both arrays, and the algorithm terminates when all these array elements are scanned, the time taken is O ( N 1 + N 2). { Algorithm 2: We can search if every element of the smallest list min(N1,N2) is present in the other list max(N1,N2). The search can be a binary search because we are given sorted lists. Without loss of generality, assume that N1 is smaller than N2. BinarySearch code can be found in page 30 of the textbook, so it is omited here. Intersection2(L1,L2) { int i=1; while (i<=N1) { if (BinarySearch(L2,L1[i],N2) printf(L1[T1]); i++; } } The binary search for a particular number takes time O (log( max ( Ni; N 2))), and it is invoked min ( N 1 ; N 2) times. Hence, total time is: O ( min ( N 1 ; N 2) log( max ( Ni; N...
View
Full Document
 Spring '09
 Algorithms, Data Structures, The Return, OTH, 12rst element t, element t position, 12rst stk nd

Click to edit the document details