0% found this document useful (0 votes)
8 views4 pages

Lec 10 - Binary Search

The document provides an overview of the Binary Search algorithm, highlighting its time complexity of O(log n) and space complexity of O(1). It includes pseudo code, Python, C++, and MATLAB implementations, as well as examples demonstrating its application in finding maximum, minimum, and second largest elements in arrays. The algorithm operates on sorted arrays by repeatedly dividing the search interval in half until the target value is found or the interval is empty.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Lec 10 - Binary Search

The document provides an overview of the Binary Search algorithm, highlighting its time complexity of O(log n) and space complexity of O(1). It includes pseudo code, Python, C++, and MATLAB implementations, as well as examples demonstrating its application in finding maximum, minimum, and second largest elements in arrays. The algorithm operates on sorted arrays by repeatedly dividing the search interval in half until the target value is found or the interval is empty.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Binary Search Algorithm

Design and Analysis of Algorithms : Lecture 10


Dr. Athar Kharal

1 Binary Search in Plain Lan- • Time complexity: O(log n).


guage • Space complexity: O(1).
Binary Search is a highly efficient search-
ing algorithm that works on sorted arrays.

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

• Array must be sorted.


left = mid + 1
• Each step eliminates half of the remaining ele-
ments. return -1 // Element not found
r
D

Examples
©

Example 1. Finding Maximum Element – Similarly: max(89, 34) = 89,


Given array: [23, 45, 12, 89, 34, 67, 56, 92, 15, 41, 78, 33, 60, 25, 50] max(67, 56) = 67
Divide & Conquer Analysis: – Max of left half = max(45, 89, 67) = 89
• Divide step: Split array into two halves Right half: (similar process)
Max of right subarray = 92
– Left half: [23, 45, 12, 89, 34, 67, 56]
– Right half: [92, 15, 41, 78, 33, 60, 25, 50] • Combine step: Compare maxima of both halves
Final result = max(89, 92) = 92
• Conquer step: Find max in each half recursively
Time Complexity Analysis:
Left half: n
T (n) = 2T + c ⇒ O(n)
– Divide further: [23, 45, 12] and 2
[89, 34, 67, 56]
– Further divide: [23], [45, 12], and [89, 34], Example 2. Finding Both Maximum and Min-
[67, 56] imum
– Compare: max(45, 12) = 45, Given array: [31, 16, 43, 28, 95, 12, 67, 54, 39, 82]
max(23, 45) = 45 Divide & Conquer Analysis:

1
Math-457: Design & Analysis of Algorithms Lecture 10

• Divide step: • Divide step:


– First half: [31, 16, 43, 28, 95] – Left half: [56, 23, 89, 44]
– Second half: [12, 67, 54, 39, 82]
– Right half: [91, 75, 63, 38]
• Conquer step: First half:
• Conquer step: Left half:
– Divide: [31, 16], [43, 28, 95]
– For [31, 16]: min = 16, max = 31 – Further divide: [56, 23], [89, 44]
– For [43, 28, 95]: min = 28, max = 95 – Track both largest and second largest:
– First half results: min = 16, max = 95 ∗ [56, 23]: L1 = 56, L2 = 23
Second half: (similar process) ∗ [89, 44]: L1 = 89, L2 = 44
Second half results: min = 12, max = 82 – Combine: L1 = 89, L2 = 56
• Combine step: Right half: (similar process)
– Overall minimum = min(16, 12) = 12 Combine: L1 = 91, L2 = 75

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
©

Figure 1: Enter Caption

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

5 while left <= right:


At

6 mid = (left + right) // 2 # Use integer division


7 if A[mid] == x:
8 return mid
9 elif A[mid] > x:
r

10 right = mid - 1
11 else:
©D

12 left = mid + 1
13

14 return -1 # Element not found

Listing 2: C++ Implementation


1 #include <iostream>
2 #include <vector>
3 using namespace std;
4

5 int binary_search(const vector<int>& A, int x) {


6 int left = 0;
7 int right = A.size() - 1;
8

9 while (left <= right) {


10 int mid = left + (right - left) / 2; // Prevents overflow
11 if (A[mid] == x) {

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

20 return -1; // Element not found


21 }
22

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

5 while left <= right


6 mid = floor((left + right) / 2);
h

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

17 index = -1; % Element not found


18 end
19

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)]);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy