forked from bellshade/Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarySearch.js
74 lines (66 loc) · 1.4 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
// Implementasi Binary Search dalam JavaScript
// Language: javascript
function binarySearchRecursive(arr, x, low = 0, high = arr.length - 1) {
const mid = Math.floor(low + (high - low) / 2);
if (high >= low) {
if (arr[mid] === x) {
return mid;
}
if (x < arr[mid]) {
return binarySearchRecursive(arr, x, low, mid - 1);
} else {
return binarySearchRecursive(arr, x, mid + 1, high);
}
} else {
return -1;
}
}
function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) {
while (high >= low) {
const mid = Math.floor(low + (high - low) / 2);
if (arr[mid] === x) {
return mid;
}
if (x < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stringArr = [
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliet",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"X-Ray",
"Yankee",
"Zulu"
];
console.log(binarySearchRecursive(arr, 3));
console.log(binarySearchIterative(arr, 7));
console.log(binarySearchRecursive(arr, 13));
console.log(binarySearchIterative(stringArr, "Whiskey"));
console.log(binarySearchRecursive(stringArr, "Zulu"));
console.log(binarySearchIterative(stringArr, "Sierra"));