-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryInrotated.js
More file actions
60 lines (38 loc) · 1.17 KB
/
Copy pathbinaryInrotated.js
File metadata and controls
60 lines (38 loc) · 1.17 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function findPivot(arr, low, high) {
if (high < low) return -1;
if (high == low) return low;
let mid = Math.floor((low + high) / 2);
if (arr[mid - 1] > arr[mid]) return mid;
if (arr[mid] > arr[mid + 1]) return mid+1;
if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1);
return findPivot(arr, mid + 1, high);
}
function BinarySearch(arr,low,high,target)
{
if(low>high)
return -1;
let mid = Math.floor((low+high)/2)
if(arr[mid] == target)
return mid;
if(arr[mid]>=target)
return BinarySearch(arr,low,mid-1,target)
return BinarySearch(arr,mid+1,high,target)
}
function rotatedSearch(arr,target) {
let pivot = findPivot(arr,0,arr.length-1)
console.log("pivot : %j",pivot)
if (pivot === -1)
return BinarySearch(arr,0,arr.length-1,target)
if(target > arr[arr.length-1])
return BinarySearch(arr,0,pivot-1,target)
else
return BinarySearch(arr,pivot,arr.length-1,target)
}
function main()
{
let arr = [5,6,0,1,2,3]
let target = 3
for (let char of arr)
console.log(rotatedSearch(arr,char+1))
}
main()