WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Data Structures & Algorithms Β· Basic Β· question 4 of 100

What is a binary search algorithm, and what is its time complexity?

πŸ“• Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers β€” PDF + EPUB for $5

A binary search algorithm is a searching algorithm that works by repeatedly dividing the search interval in half. It is a very efficient algorithm for finding a particular value in a sorted array or list.

The binary search algorithm works as follows:

Here is an example of how to implement a binary search algorithm in Java:

public static int binarySearch(int[] arr, int target) {
    int low = 0;
    int high = arr.length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1;
}

In this example, the binarySearch() method takes an array of integers and a target value as parameters. It then initializes the low and high variables to the first and last indices of the array, respectively. The method then enters a loop where it calculates the middle index of the search interval and compares the target value to the element at the middle index. Depending on the comparison, the search interval is either halved by setting the high or low variable to mid+1 or mid-1, respectively. The loop continues until the target value is found, or until the search interval is empty. If the target value is not found, the method returns -1.

The time complexity of the binary search algorithm is O(log n), where n is the size of the array or list being searched. This is because the search interval is halved with each iteration of the loop, which reduces the number of elements that need to be searched by half at each step. Therefore, the time it takes to find the target value grows logarithmically with the size of the array or list.

In summary, the binary search algorithm is a very efficient algorithm for finding a particular value in a sorted array or list. It has a time complexity of O(log n), making it a very fast algorithm for searching large datasets.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview β€” then scores it.
πŸ“ž Practice Data Structures & Algorithms β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers β€” PDF + EPUB for $5

All 100 Data Structures & Algorithms questions Β· All topics