-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.js
More file actions
36 lines (35 loc) · 813 Bytes
/
Copy pathBinarySearch.js
File metadata and controls
36 lines (35 loc) · 813 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
36
/**
@description To find a element from a Sorted List using Binary search
@param List
@param ItemToFind
@returns Int
*/
function BinarySearch(List, Target) {
let Begin = 0,
Last = List.length - 1;
while (Begin <= Last) {
let mid = Number.parseInt(Begin + (Last - Begin) / 2);
let MiddleElement = List[mid];
console.log(`Middle element : ${MiddleElement}`);
if (MiddleElement < Target) {
Begin = mid + 1;
} else if (MiddleElement > Target) {
Last = mid - 1;
} else {
return mid;
}
}
return -1;
}
let listy = [];
for (let index = 0; index < 10000000; index++) {
listy.push(index);
}
const test = BinarySearch(listy, 676767);
if (test === 676767) {
console.log(`Test result: ${test}`);
console.log("Found!");
} else {
console.log(`Test result: ${test}`);
console.log("Failed!");
}