-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.html
More file actions
55 lines (51 loc) · 1.41 KB
/
Copy pathbinary_search.html
File metadata and controls
55 lines (51 loc) · 1.41 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Binary Search</h1>
<script>
let data = [5, 9, 13, 17, 45, 67, 89, 100];
let find = 89;
let start = 0;
let end = data.length - 1;
let position = undefined;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
// console.warn(data[mid]);
if (data[mid] === find) {
position = mid;
break;
} else if (data[mid] < find) {
start = mid + 1;
} else {
end = mid - 1;
}
}
console.warn(position);
console.log(Math.floor(1.5));
// Recursive Binary search
// let data = [10, 15, 18, 34, 67, 70, 89];
// let start = 0;
// let end = data.length - 1;
// let find = 15;
// let position = undefined;
function recursiveBinary(data, start, end) {
mid = Math.floor((start + end) / 2);
if (data[mid] === find) {
position = mid;
return true;
} else if (data[mid] < find) {
recursiveBinary(data, mid + 1, end);
} else {
recursiveBinary(data, start, mid - 1);
}
}
recursiveBinary(data, start, end);
console.warn(position);
</script>
</body>
</html>