Skip to content

Commit 0175ecd

Browse files
appgurueuPanquesito7vbrazo
authored
Fix binary search explanation (#138)
* Fix binary search explanation Elaborate on the possible return values if the element is not found, correct the space complexity claim for recursive implementations. * Fix typo Co-authored-by: David Leal <halfpacho@gmail.com> * add articles Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: Vitor Oliveira <vbrazo@gmail.com>
1 parent 3d6e461 commit 0175ecd

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

en/Search Algorithms/Binary Search.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,17 @@ Given a sorted array of n elements, write a function to search for the index of
1212
- If it is equal to the target element then return the index
1313
- Else if it is greater than the target element then consider only the left half of array. (lower index = 0, higher = middle - 1)
1414
- Else if it is less than the target element then consider only the right half of array. (lower index = middle + 1, higher = length of array)
15-
- Return -1 if target element is not found in the array (Base Case: If lower index is greater than or equal to higher index)
15+
- Return -(insertion index + 1) if the target element is not found in the array (If the lower index is greater than or equal to higher index). Some simpler implementations just return -1 if the element is not found. The offset of 1 must be added as the insertion index might be 0 (the searched value might be smaller than all elements in the array). As indexing starts at 0, this must be distinguishable from the case where the target element has the index 0.
1616

1717
#### Time Complexity
1818

19-
O(log n) Worse Case
19+
O(log n) Worst Case
2020
O(1) Best Case (If middle element of initial array is the target element)
2121

2222
#### Space Complexity
2323

2424
O(1) For iterative approach
25-
O(log n) For recursive approach due to recursion call stack
25+
O(1) For recursive approach *if tail call optimization is used*, O(log n) due to recursion call stack, otherwise
2626

2727
#### Example
2828

@@ -35,7 +35,7 @@ array i.e. [1,2,3].
3535
Here we find the middle element equal to target element so we return its index i.e. 1
3636
3737
target = 9
38-
Binary Search should return -1 as 9 is not present in the array
38+
A simple Binary Search implementation may return -1 as 9 is not present in the array. A more complex one would return the index at which 9 would have to be inserted, which would be `-8` (last position in the array (7) plus one (7+1), negated)`.
3939
```
4040

4141
#### Code Implementation Links

0 commit comments

Comments
 (0)