Skip to content

Commit 1861a87

Browse files
committed
feat: add exponential search
1 parent d4dba63 commit 1861a87

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

search/exponential_search.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @description Exponential search algorithm for a sorted array.
3+
*
4+
* The algorithm searches for a specific value in a sorted array by first finding a range
5+
* where the value may be present and then performing a binary search within that range.
6+
*
7+
* @param {number[]} array - sorted list of numbers
8+
* @param {number} x - target number to search for
9+
* @return {number | null} - index of the target number in the list, or null if not found
10+
* @see [ExponentialSearch](https://www.geeksforgeeks.org/exponential-search/)
11+
* @example exponentialSearch([1, 2, 3, 4, 5], 3) => 2
12+
* @example exponentialSearch([10, 20, 30, 40, 50], 35) => null
13+
*/
14+
15+
export const exponentialSearch = (
16+
array: number[],
17+
x: number
18+
): number | null => {
19+
const arrayLength = array.length;
20+
if (arrayLength === 0) return null;
21+
22+
if (array[0] === x) return 0;
23+
24+
let i = 1;
25+
while (i < arrayLength && array[i] <= x) {
26+
i = i * 2;
27+
}
28+
29+
return binarySearch(array, x, i / 2, Math.min(i, arrayLength - 1));
30+
};
31+
32+
const binarySearch = (
33+
array: number[],
34+
x: number,
35+
start: number,
36+
end: number
37+
): number | null => {
38+
while (start <= end) {
39+
const mid = Math.floor((start + end) / 2);
40+
if (array[mid] === x) {
41+
return mid;
42+
} else if (array[mid] < x) {
43+
start = mid + 1;
44+
} else {
45+
end = mid - 1;
46+
}
47+
}
48+
return null;
49+
};
50+

0 commit comments

Comments
 (0)