diff --git a/search/binary_search.ts b/search/binary_search.ts index 39d380a4..2d18dca8 100644 --- a/search/binary_search.ts +++ b/search/binary_search.ts @@ -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 diff --git a/search/exponential_search.ts b/search/exponential_search.ts index 0b1a2ddf..19c3409f 100644 --- a/search/exponential_search.ts +++ b/search/exponential_search.ts @@ -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 @@ -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 }