⬅ Previous Topic
Find Maximum Product SubarrayNext Topic ⮕
Find Lower Bound in Sorted Array⬅ Previous Topic
Find Maximum Product SubarrayNext Topic ⮕
Find Lower Bound in Sorted ArrayTopic Contents
You are given a sorted array of integers and a target
number. Your task is to find the index of the target number using the binary search algorithm, implemented in an iterative way (using loops instead of recursion).
Binary search works only when the array is sorted in ascending order. If the target exists in the array, return its index. Otherwise, return -1
.
arr
and a target
value.low = 0
and high = arr.length - 1
.low ≤ high
:mid = Math.floor((low + high) / 2)
.arr[mid] == target
, return mid
(target found).arr[mid] < target
, set low = mid + 1
.high = mid - 1
.-1
(not found).def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# Sample Input
arr = [1, 3, 5, 7, 9, 11]
target = 7
print("Index:", binary_search(arr, target))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The target element is found at the middle index on the first comparison. |
Average Case | O(log n) | The search space is divided in half during each iteration until the target is found or determined to be absent. |
Average Case | O(log n) | The target is located at the very beginning or end, or is not in the array, requiring the full depth of the binary search process. |
O(1)
Explanation: The algorithm uses constant space. It only maintains a few variables (like low, high, and mid) and does not allocate extra space based on input size.
⬅ Previous Topic
Find Maximum Product SubarrayNext Topic ⮕
Find Lower Bound in Sorted ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.