Lec 10 - Binary Search
Lec 10 - Binary Search
l
Pseudo Code
ra
Think of it as finding a word in a dictio-
nary:
Algorithm BinarySearch(array, target):
ha
1. Open the dictionary in the middle. left = 0
2. If the word you want is before the right = length(array) - 1
middle word, look in the first half.
K
while left <= right:
3. If it comes after, look in the second mid = (left + right) / 2
half.
4. Repeat this process until you find
r
if array[mid] equals target:
your word. return mid
ha
else if array[mid] > target:
Key Points: right = mid - 1
else:
At
Examples
©
1
Math-457: Design & Analysis of Algorithms Lecture 10
l
ra
– Overall maximum = max(95, 82) = 95 • Combine step:
Time Complexity:
– Overall L1 = 91
ha
n
T (n) = 2T + 2 ⇒ O(n) – Second largest = max(89, 75) = 89
2
Note: This approach is more efficient than finding
max and min separately.
Example 3. Finding Second Largest Element
K
Time Complexity:
T (n) = 2T
n
+ c ⇒ O(n)
ar
2
Given array: [56, 23, 89, 44, 91, 75, 63, 38]
Divide & Conquer Analysis:
h
At
Dr
©
2
Math-457: Design & Analysis of Algorithms Lecture 10
Algorithm
Input: A sorted array A[0...n − 1] and target value x
Output: Index of x in A or −1 if not found
left ← 0 ;
right ← n - 1 ;
while left ≤ right do
mid ← ⌊(left + right)⌋ / 2;
if A[mid] = x then
return mid;
else
if A[mid] > x then
right ← mid - 1;
else
left ← mid + 1;
end
al
end
end
return -1;
ar
Algorithm 1: Binary Search Algorithm
Implementations
Kh
Listing 1: Python Implementation
r
1 def binary_search(A, x):
2 left = 0
ha
3 right = len(A) - 1
4
10 right = mid - 1
11 else:
©D
12 left = mid + 1
13
3
Math-457: Design & Analysis of Algorithms Lecture 10
12 return mid;
13 } else if (A[mid] > x) {
14 right = mid - 1;
15 } else {
16 left = mid + 1;
17 }
18 }
19
23 // Example usage
24 int main() {
25 vector<int> A = {1, 3, 5, 7, 9};
26 int x = 7;
27 int result = binary_search(A, x);
l
28 cout << "Index of " << x << ": " << result << endl;
ra
29 return 0;
30 }
ha
Listing 3: MATLAB Implementation
1
3
function index = binary_search(A, x)
left = 1;
right = length(A); K
ar
4
7 if A(mid) == x
At
8 index = mid;
9 return;
10 elseif A(mid) > x
11 right = mid - 1;
Dr
12 else
13 left = mid + 1;
14 end
©
15 end
16
20 % Example usage
21 A = [1, 3, 5, 7, 9];
22 x = 7;
23 result = binary_search(A, x);
24 disp([’Index of ’, num2str(x), ’: ’, num2str(result)]);