10.07.2015 Views

Divide and Conquer

Divide and Conquer

Divide and Conquer

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Divide</strong> <strong>and</strong> <strong>Conquer</strong> 6∗ We can describe the recurrence for mergesort asT n = 2T n2 + Θ(n)∗ Omitting the value of T 1 changes the exact solution for the recurrence, but not by more than a constant factor;it has no effect on the order of growthBinary search• Input characterized by an array a i , 0 ≤ i < n– Elements in a are sorted in nondecreasing order– Problem to determine whether an element k is present in a∗ If it is present, return its index j such that a j = k∗ If the element is not present, return −1• Instance of problem given byP = (n, a l , . . . , a r , k)where a l , . . . , a r are n elements in the list to be searched for k• Assume small ( P ) is true if r == l– There is only one element to be tested– In this case, solution ( P ) returns i if a i = x; otherwise it returns −1– g(1) = Θ(1)• If r − l ≥ 1, compute m = (l + r)/2 leading to three cases1. a m = k– Problem is immediately solved2. a m < k– Discard the elements whose index is smaller than m– Search for k in a[m + 1..r]3. a m > k– Discard the elements whose index is larger than m– Search for k in a[l..m − 1]• Case 2 <strong>and</strong> 3 result in only one subproblem; division takes Θ(1) time– Answer to the remaining subproblem is also the answer to the original problem; no need to combine the solutions• Problem initially invoked by bin_search ( a, 1, n, k );• Recursive Algorithm// Given an array a[l..r] of elements in nondecreasing order, 0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!