-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
48 lines (38 loc) · 834 Bytes
/
Copy pathsearch.js
File metadata and controls
48 lines (38 loc) · 834 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
37
38
39
40
41
42
43
44
45
46
47
48
// creating big array
let arr = [];
for (let i = 0; i < 100000; i++) {
arr.push(i);
}
// search via method find
function search(arr, number) {
return arr.find(el => el === number)
}
// search via cycle
function searchS(arr, number) {
for (const el of arr) {
if (el === number) return el;
};
}
// binary search
function searchB(arr, number) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = (low + high) / 2;
if (mid % 2 !== 0) mid = Math.ceil(mid);
let guess = arr[mid];
if (guess === number) return mid;
if (guess < number) low = mid + 1;
if (guess > number) high = mid - 1;
}
}
const num = 70010;
console.time();
search(arr, num)
console.timeEnd();
console.time();
searchS(arr, num)
console.timeEnd();
console.time();
searchB(arr, num)
console.timeEnd();