SE Sem IV AoA Lab Experiment 5 202425
SE Sem IV AoA Lab Experiment 5 202425
5
To implement Binary Search Algorithm
Date of Performance:
Date of Submission:
Theory:
Binary search is a highly efficient algorithm used to locate a target value within a
sorted array. It works by repeatedly dividing the search interval in half until the target
value is found or the search interval is empty.
Working Principle:
Binary search relies on the fact that the array is sorted. It compares the target value
with the middle element of the array. If the target value matches the middle element,
the search is successful. If the target value is less than the middle element, the search
continues on the left half of the array. If the target value is greater, the search
continues on the right half.
Step 1:
Initialize two pointers, low and high, to the first and last indices of the array
respectively.
Step 2:
Repeat the following steps until low is less than or equal to high.
Step 3:
If the search interval becomes empty (i.e., low exceeds high), the target value is not
present in the array. Return a sentinel value (e.g., -1) to indicate that the value was
not found.
Example:
Let's say we want to search for the value 12 in array [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Initialize two pointers, low and high, to the first and last indices of the array.
mid = (5 + 6) / 2
= 5.
Result:
Binary search algorithm successfully located the target value 12 in the array.
• In binary search, the key is initially compared to the array’s middle element.
• If the key is in the center of the array, the algorithm only does one comparison,
regardless of the size of the array.
Worst Case:
• Every iteration, the binary search, search space is decreased by half, allowing for
maximum log2n array divisions.
• If the key is at the leaf of the tree or it is not present at all, then the algorithm does
log2n comparisons, which is maximum.
• The problem size is reduced by a factor of two after each iteration, and the
method does one comparison.
• In every iteration, the binary search does one comparison and creates a new
problem of size n/2.
• Only one comparison is needed when there is only one element in the array.
T(n/4) = T(n/8) + 1
T(n) = T(n/23) + 3
.....
After k iterations,
Assume, n/ 2k =1 so, n = 2k
{ Using log22 = 1 }
T(n) = O(log2n)
Average Case:
• The average case for binary search occurs when the key element is neither in the
middle nor at the leaf level of the search tree.
• On average, it does half of the log2 n comparisons, which will turn out as
T (n) = O(log2 n).
• The complexity of linear search and binary search for all three cases is compared
in the following table.
Code:
Output: