PowerShell Script to Perform Binary Search on Sorted Array
BinarySearch($arr, $target) that repeatedly checks the middle element and narrows the search range until the target is found or the range is empty.Examples
How to Think About It
Algorithm
Code
function BinarySearch($arr, $target) { $low = 0 $high = $arr.Length - 1 while ($low -le $high) { $mid = [math]::Floor(($low + $high) / 2) if ($arr[$mid] -eq $target) { return $mid } elseif ($arr[$mid] -lt $target) { $low = $mid + 1 } else { $high = $mid - 1 } } return -1 } # Example usage $arr = @(1, 3, 5, 7, 9) $target = 5 $result = BinarySearch $arr $target Write-Output "Index of $target is $result"
Dry Run
Let's trace searching for 5 in [1, 3, 5, 7, 9] through the code
Initialize
low=0, high=4 (array length - 1)
First middle check
mid = (0+4)/2 = 2, arr[2] = 5 matches target 5, return 2
| low | high | mid | arr[mid] | action |
|---|---|---|---|---|
| 0 | 4 | 2 | 5 | Found target, return index 2 |
Why This Works
Step 1: Divide and conquer
The code splits the array into halves by calculating the middle index with mid = (low + high) / 2.
Step 2: Compare middle element
It compares the middle element with the target using -eq and decides which half to keep searching.
Step 3: Adjust search range
If the middle element is less than the target, it moves the low pointer up; otherwise, it moves the high pointer down.
Step 4: Return result
If the target is found, it returns the index; if not, it returns -1 to indicate absence.
Alternative Approaches
function RecursiveBinarySearch($arr, $target, $low, $high) { if ($low -gt $high) { return -1 } $mid = [math]::Floor(($low + $high) / 2) if ($arr[$mid] -eq $target) { return $mid } elseif ($arr[$mid] -lt $target) { return RecursiveBinarySearch $arr $target ($mid + 1) $high } else { return RecursiveBinarySearch $arr $target $low ($mid - 1) } } $arr = @(1,3,5,7,9) $result = RecursiveBinarySearch $arr 5 0 ($arr.Length - 1) Write-Output "Index of 5 is $result"
$arr = @(1,3,5,7,9) $target = 5 $result = [Array]::IndexOf($arr, $target) Write-Output "Index of $target is $result"
Complexity: O(log n) time, O(1) space
Time Complexity
Binary search halves the search space each step, so it runs in logarithmic time relative to the array size.
Space Complexity
The iterative version uses constant extra space, only storing a few variables for indexes.
Which Approach is Fastest?
Iterative binary search is fastest and most memory efficient; recursive is easier to read but uses more stack space; linear search is slowest.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative Binary Search | O(log n) | O(1) | Large sorted arrays, memory efficient |
| Recursive Binary Search | O(log n) | O(log n) | Readable code, small to medium arrays |
| Linear Search | O(n) | O(1) | Unsorted or small arrays |