For this week's coding challenge, I implemented the Binary Search algorithm using an iterative approach.
For this week's coding challenge, I implemented the Binary Search algorithm using an iterative approach.
Binary Search is a classic "Divide and Conquer" algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array and eliminates the half in which the target cannot lie.
- Data Generation: I used
NumPyto generate a random list size (n) and random integers. - Sorting: The list is sorted using
np.sort()(Crucial step: Binary Search only works on sorted data). - The Loop: - We define
lowandhighpointers.- We calculate the
midpoint:(low + high) // 2. - If
arr[mid] == target, we return the index. - If
arr[mid] > target, we discard the right half. - If
arr[mid] < target, we discard the left half.
- We calculate the
- Tracking: The script prints every attempt to demonstrate how quickly the algorithm narrows down the search.
-
Time Complexity:
$O(\log n)$ - Logarithmic time. Even with a largen, the number of attempts grows very slowly. -
Space Complexity:
$O(1)$ - Iterative implementation (uses constant extra space).
- Python 3.14.2
- NumPy