forked from vJechsmayr/JavaScriptAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexponentialSearch.js
More file actions
35 lines (26 loc) · 771 Bytes
/
Copy pathexponentialSearch.js
File metadata and controls
35 lines (26 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
let binarySearch = function (arr, x, start, end) {
// Base Condtion
if (start > end) return false;
// Find the middle index
let mid=Math.floor((start + end)/2);
// Compare mid with given key x
if (arr[mid]===x) return true;
// If element at mid is greater than x,
// search in the left half of mid
if(arr[mid] > x)
return recursiveFunction(arr, x, start, mid-1);
else
// If element at mid is smaller than x,
// search in the right half of mid
return recursiveFunction(arr, x, mid+1, end);
}
function exponentialSearch(arr, x, length){
if (arr[0] == x){
return 0;
}
var i = 1;
while (i < length && arr[i] <= x){
i = i*2;
}
return binarySearch(arr, x, i/2, Math.min(i, length-1));
}