Skip to content

Commit

Permalink
fix: added parameters to iterative binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
Fechuli committed Aug 4, 2024
1 parent 44b698d commit 61b1d22
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 25 deletions.
12 changes: 6 additions & 6 deletions search/binary_search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,18 @@

export const binarySearchIterative = (
array: number[],
target: number
target: number,
start: number = 0,
end: number = array.length - 1
): number => {
if (array.length === 0) return -1

// declare pointers for the start, middle and end indices
let start = 0,
end = array.length - 1,
middle = (start + end) >> 1

// ensure the target is within the bounds of the array
if (target < array[start] || target > array[end]) return -1

// declare pointers for the middle index
let middle = (start + end) >> 1

while (array[middle] !== target && start <= end) {
// if the target is less than the middle value, move the end pointer to be middle -1 to narrow the search space
// otherwise, move the start pointer to be middle + 1
Expand Down
30 changes: 11 additions & 19 deletions search/exponential_search.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { binarySearchIterative } from './binary_search'

/**
* @description Exponential search algorithm for a sorted array.
*
* The algorithm searches for a specific value in a sorted array by first finding a range
* where the value may be present and then performing a binary search within that range.
*
* Compared with binary search, exponential search can be more convenient and advantageous
* in cases where the element to be searched is closer to the beginning of the array,
* thus avoiding several comparisons that would make the search more verbose.
* Exponential search doubles the search time with each iteration.
*
* @param {number[]} array - sorted list of numbers
* @param {number} x - target number to search for
* @return {number | null} - index of the target number in the list, or null if not found
Expand All @@ -26,24 +33,9 @@ export const exponentialSearch = (
i = i * 2
}

return binarySearch(array, x, i / 2, Math.min(i, arrayLength - 1))
}
const start = Math.floor(i / 2)
const end = Math.min(i, arrayLength - 1)
const result = binarySearchIterative(array, x, start, end)

const binarySearch = (
array: number[],
x: number,
start: number,
end: number
): number | null => {
while (start <= end) {
const mid = Math.floor((start + end) / 2)
if (array[mid] === x) {
return mid
} else if (array[mid] < x) {
start = mid + 1
} else {
end = mid - 1
}
}
return null
return result !== -1 ? result : null
}

0 comments on commit 61b1d22

Please sign in to comment.