Unit 2 (Divide and Conquer) (Part 2)
Unit 2 (Divide and Conquer) (Part 2)
a problem of
size n
(instance)
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
• Binary search
• Quick sort
• Merge sort
• Strassen’s matrix multiplication
Binary Search
Binary Search: Iterative Algorithm
Binary Search: Recursive Algorithm
Binary Search
Binary search is used to search for an element in a sorted array.
Procedure:
1. Take a sorted array ( increasing order ) and initialize: low = starting index and
high = end index of the array.
2. Repeat the following process when low <= high
2.1 Calculate the middle index as mid = ( low + high ) / 2
2.2 Comparing searching element with the middle element
if searching element == middle element
return the middle index (element found)
if searching element < middle element
high = mid - 1 ( search the left half )
if searching element > middle element
low = mid + 1 ( search the right half )
3. If low > high return 0 ( element not found )
Problem 1: Binary Search
Consider the following elements and search for the element 151
-6 low= 2, high=2
mid = 4/2 = 2
-14 < a[2] high=mid-1=1
7 9 23 low=4, high=6
mid=10/2=5
9 == a[5]
Element 9 is found
Problem 1: Binary Search Cont…
BINARY SEARCH (Contd..)
Problem 2: n = 9
A(j : n) are -15, -6, 0, 7, 9, 23, 54, 82, 101. x is 101, -14, 82
Case 1 Case 2 Case3
x=101 x= -14 x=82
i l mid i l mid i l mid
1 9 5 1 9 5 1 9 5
6 9 7 1 4 2 6 9 7
8 9 8 1 1 1 5 9 8
9 9 9 2 1
found at 9 not found found at 8
22
Problem 2: Binary Search Cont…
Analysis
Let T(n) be the number of comparisons in worst-case in an array of n elements.
Hence,
● Merge Algorithm
Merge algorithm is used to merge two subarrays into a array by
comparing the elements in each of the subarrays in the following way:
● Compare the first element of two subarrays.
● Move the smaller element to the new array (temporary).
● Move to the next element in the subarray from which the element was
taken.
● Repeat until all elements of two subarrays are in the new array.
● Copy new array back to the original array.
h = 3; i = 3; j = 4;
if( a[3] ≤ a[4]) // 310 ≤ 351 i 1 2 3
// updated values to loop
// while((h ≤ 3) and (j ≤ 5)) do b[3] = a[3]; h = 4; b 179 285 310
i = 4;
h = 4; i = 4; j = 4;
// updated values to loop //loop condition false
//while((h ≤ 3) and (j ≤ 5)) do
if( 4 > 3) // true // for iteration k = 4
b[4] = a[4]; i = 5 i 1 2 3 4 5
for k = 4 to 5 do
b[ i ] = a[ k ]; i = i+1 // for iteration k = 5 b 179 285 310 351 652
b[5] = a[5]; i = 6
//copying from b to a i 1 2 3 4 5
for k=1 to 5 do a[k] = b[k] // b→ temporary array a 179 285 310 351 652
// a→original array
Tree of calls of Merge
Time Complexity: Merge Sort