Binary Search Algorithm
Introduction
Binary Search is an efficient searching algorithm used to find the position of an element in a sorted array. It is widely used in computer science because it reduces the number of comparisons and saves time. Binary Search is an important topic for data structures exams, interviews, and competitive programming.
What is Binary Search Algorithm?
Binary Search is a searching technique that works by dividing the search space into half in every step. Instead of checking elements one by one, it compares the target value with the middle element of the array.
⚠️ Important condition:
Binary Search works only on sorted data.
How Binary Search Works
The algorithm follows these steps:
-
Find the middle element of the array
-
Compare the middle element with the search key
-
If the key is equal to the middle element → search successful
-
If the key is smaller → search in the left half
-
If the key is larger → search in the right half
-
Repeat until the element is found or the range becomes empty
Example of Binary Search
Consider a sorted array:
Search key = 40
-
Middle element = 30
-
Since 40 > 30, search in right half
-
New middle = 40
-
Element found
👉 Position of 40 = index 3
Binary Search Algorithm (Steps)
-
Set low = 0
-
Set high = n – 1
-
Find mid = (low + high) / 2
-
Compare key with array[mid]
-
Update low or high accordingly
Time Complexity of Binary Search
-
Best case: O(1)
-
Average case: O(log n)
-
Worst case: O(log n)
This makes Binary Search much faster than Linear Search.
Advantages of Binary Search
-
Faster searching
-
Less number of comparisons
-
Efficient for large datasets
Disadvantages of Binary Search
-
Works only on sorted arrays
-
Not suitable for linked lists
-
Sorting may take extra time
Applications of Binary Search
-
Searching elements in large databases
-
Used in libraries and dictionaries
-
Used in computer algorithms
-
Useful in competitive programming
Conclusion
Binary Search is a powerful and efficient searching algorithm. By dividing the search space into half, it significantly reduces execution time. Understanding Binary Search is essential for data structures exams and technical interviews.


Comments
Post a Comment