Binary Search Algorithm Explained

Binary Search Algorithm Explained:


Let us consider a scenario. Suppose, you have a book of 1000 pages and we need to go to page number 580 and check whether the page exists or not. By using the linear search algorithm, you can start looking for the desired page from the beginning or the end. In both ways, you have to search over a large number of pages to find page number 580 as we are checking every page on our way. But, can we do it better? Can we find our desired page by making fewer comparisons? The answer is: Yes, we can do it in a faster way. We can do the improvement in less time by using the “Binary Search Algorithm”. First, we need to keep in mind that this algorithm can be correctly applied if the data is sorted. In the case of page numbers of a book, the data is sorted. Here, we have page numbers from 1 to 1000 in a sorted manner. We need to find page number 580. Let’s divide our searching area into two halves. Get the midpoint of range 1 to 1000 like this, mid-index = (ending index+starting index-1)/2. So, it goes like this,(1000 / 2) = 500. Compare 500 (mid-index) with 580 (searching index). 580 is larger than 500 so it cannot be present in the range (1- 500). So, let’s exclude it from our searching area. Now, we have (501–1000) numbered pages for searching. Repeat the previous process and get the midpoint of the range (501 -1000). It will be 750. Compare 580 again with 750. And fix the new searching area as (501 -750) and exclude the range in which the number cannot be present. Keep repeating the process until you find the exact number or reach a situation when there are no numbers left to search. In this process, you can find the desired number in log(n) time and you need to perform a very fewer number of comparisons than linear search as after every comparison we are making our searching area small by excluding areas in which searching is unnecessary. So, the method is very simple when you have a sorted data set and need to find something in the data set rather than keep checking every element in the data set one by one, keep dividing the data set into two halves and compare the value with mid-value.

This algorithm is frequently used in small to big tasks in computer science. Some other important algorithms like Merge Sort also use the concept of divide and conquer. If you understand this algorithm well, you will get the basic idea of the “Divide & Conquer” paradigm which is surely going to help you in learning more complex algorithms in the future. The most important thing to remember is, whenever you are going to apply the binary search algorithm the data must be placed in a sorted manner otherwise you cannot apply binary search. If you are going to start competitive programming must know the binary search algorithm as you will find problems that needed to be solved by directly using the binary search algorithm or using the concept of the binary search algorithm.

⭐ I have attached here my code implementation of the binary search algorithm in Python & C++ programming language ⭐

✴️ Code Implementation in Python

def main():
    given_array = [1, 2, 3, 5, 8, 9, 11]
    find = 8  # Number to search.
    number_found = False  # Determines if the number is found or not.
    start_index = 0
    end_index = len(given_array) - 1
    while end_index > start_index:
        mid_index = (end_index + start_index - 1) // 2
        if given_array[mid_index] == find:
            number_found = True
        elif given_array[mid_index] > find:
            end_index = mid_index - 1

            start_index = mid_index + 1

    if number_found:
        print("The Desired Element Is Present!")
        print("The Desired Element Is Not Present")

if __name__ == "__main__":

✴️ Code Implementation in C++


using namespace std;

int main()
    int arr[5]= {1, 4, 6, 8, 9, 10, 12}; // given array.
    int y = 9; // Element to search is stored in variable y.
    int l = 0;  // l = Lower Index
    int h = n; // h = Higher Index
    int m; // m = Middle Index

    // Start of the loop to perform "Binary Search Algorithm".
    while(l <= h) // The loop will run until there is one element left in array.
        m = (l + h)/2; // Find the mid to divide the array into two almost equal parts.

        if(y == arr[m]) // If the element is in the mid, we found it!
            break;  // Break the loop.

        if(y  h)
        printf( "%d not found\n", y);
        printf( "%d found!", y);


So far, I’ve tried to show everything steps by step, and below, the discussion section is open for your opinion to share and of course the questions if any. And don’t forget to follow us.

from Tumblr

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s