Question bank

How do you implement a binary search function for a sorted array?

January 1, 20254 min read
MediumCodingProgrammingProblem-SolvingAlgorithm DesignSoftware EngineerData Scientist
How do you implement a binary search function for a sorted array?

Approach Implementing a binary search function for a sorted array involves a structured approach that ensures efficiency and clarity. Here’s a clear framework for tackling this problem: Understand the Problem : Recognize that binary search is an algorithm…

Approach

Implementing a binary search function for a sorted array involves a structured approach that ensures efficiency and clarity. Here’s a clear framework for tackling this problem:

  1. Understand the Problem: Recognize that binary search is an algorithm that finds the position of a target value within a sorted array.
  2. Identify Input and Output:
  • Input: A sorted array and a target value.
  • Output: The index of the target value in the array or a signal that the value is not present.
  • Choose the Right Method: Decide whether to use an iterative or recursive approach based on the context and requirements.
  • Implement the Algorithm:
  • Initialize two pointers: low and high.
  • Calculate the midpoint and compare the midpoint value to the target.
  • Adjust pointers based on the comparison until the target is found or pointers converge.

Key Points

  • Efficiency: Binary search operates in O(log n) time complexity, making it much faster than linear search for large datasets.
  • Pre-condition: The array must be sorted prior to applying binary search.
  • Edge Cases: Handle scenarios where the array is empty or contains only one element.

Standard Response

Below is a sample implementation of a binary search function in Python, along with an explanation of how it works:

def binary_search(sorted_array, target):
 low = 0
 high = len(sorted_array) - 1

 while low <= high:
 mid = (low + high) // 2
 
 # Check if target is present at mid
 if sorted_array[mid] == target:
 return mid # Target found
 elif sorted_array[mid] < target:
 low = mid + 1 # Target is in the upper half
 else:
 high = mid - 1 # Target is in the lower half
 
 return -1 # Target not found

Explanation of the Code:

  • Initialization:
  • Set low to the first index (0) and high to the last index (len(sorted_array) - 1).
  • Loop Until Found:
  • Use a while loop to continue searching while low is less than or equal to high.
  • Calculate Midpoint:
  • Calculate the midpoint index using integer division.
  • Comparison:
  • If the midpoint value equals the target, return the midpoint index.
  • If the midpoint value is less than the target, adjust the low pointer to mid + 1.
  • If the midpoint value is greater than the target, adjust the high pointer to mid - 1.
  • End Condition:
  • If the loop ends without finding the target, return -1 to indicate that the target is not in the array.

This implementation is clear, efficient, and can be adapted to various programming languages with minimal changes.

Tips & Variations

Common Mistakes to Avoid

  • Not Checking Sorted Order: Ensure the input array is sorted; otherwise, the algorithm will not work correctly.
  • Incorrect Midpoint Calculation: Always use integer division to avoid floating-point indices.
  • Infinite Loops: Ensure the loop condition is correctly set to avoid infinite loops.

Alternative Ways to Answer

  • Recursive Approach: A recursive version of binary search can be implemented as follows:
def binary_search_recursive(sorted_array, target, low, high):
 if low > high:
 return -1 # Base case: target not found

 mid = (low + high) // 2

 if sorted_array[mid] == target:
 return mid # Target found
 elif sorted_array[mid] < target:
 return binary_search_recursive(sorted_array, target, mid + 1, high) # Search in upper half
 else:
 return binary_search_recursive(sorted_array, target, low, mid - 1) # Search in lower half

Role-Specific Variations

  • Technical Positions: Emphasize the efficiency of the algorithm and discuss its applications in data structures.
  • Managerial Roles: Frame the discussion around problem-solving skills and the importance of algorithms in decision-making.
  • Creative Roles: Highlight the logic and analytical thinking involved in algorithm design, relating it to creative problem-solving.

Follow-Up Questions

  • What are the time and space complexities of binary search?
  • Can you explain the difference between binary search and linear search?
  • How would you modify the algorithm to return all occurrences of a target value?
  • What would you do if the array is very large and doesn't fit into memory?

By preparing for these

VA

Verve AI Editorial Team

Question Bank