-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.js
75 lines (41 loc) · 1.71 KB
/
BinarySearch.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function orderAgnosticBinarySearch(array,target){
let start = 0;
let end = array.length - 1;
if(array[0] <= array[end]){ // Array is sorted in Ascending Order
while(start <= end){
let mid = Math.floor(((start + end) / 2));
if(array[mid] == target){
// If the element is present in the Array
const result = `The given target element is present in index ${mid} of the provided array.`;
return result;
}else if(target < array[mid]){
end = mid - 1;
}else{
start = mid + 1
}
}
// If the element is not present in the Array
const result = `The given element: ${target} is not present in the provided array.`;
return result;
}else{ // Array is sorted in Descending Order
while(start <= end){
let mid = Math.floor(((start + end) / 2));
if(array[mid] == target){
// If the element is present in the Array
const result = `The given target element is present in index ${mid} of the provided array.`;
return result;
}else if(target < array[mid]){
start = mid + 1;
}else{
end = mid - 1
}
}
// If the element is not present in the Array
const result = `The given element: ${target} is not present in the provided array.`;
return result;
}
}
let arr1 = [10,20,30,40,50,60];
let arr2 = [60,50,40,30,20,10];
const resultOfSearch = orderAgnosticBinarySearch(arr1,50);
console.log(resultOfSearch);