Skip to content

Instantly share code, notes, and snippets.

@Nilesh-Saini-09
Created June 24, 2022 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilesh-Saini-09/173a62a07b96540a8c4c5f8325291ca8 to your computer and use it in GitHub Desktop.
Save Nilesh-Saini-09/173a62a07b96540a8c4c5f8325291ca8 to your computer and use it in GitHub Desktop.
Exponential Search
// ES6 Arrow Function
const exponentialSearch = (arr, x) => {
let n = arr.length;
// If x is present at first location itself
if (arr[0] == x) return 0;
// Find range for binary search by
// repeated doubling
let i = 1;
while (i < n && arr[i] <= x) {
i = i*2;
}
// Call binary search for the found range.
return binarySearch(arr, i/2, Math.min(i, n), x);
}
// Binary Search
const binarySearch = (arr, l, r, x) => {
if (r >= l) {
let mid = l + (r - l) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
// let testArray = [1,2,3,4,5,6,7,8,9,10];
// let x = 9;
// exponentialSearch(testArray, x);
// output => 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment