-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.js
More file actions
70 lines (47 loc) · 1.6 KB
/
Copy pathbinarysearch.js
File metadata and controls
70 lines (47 loc) · 1.6 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
let items = "000001111111122223456448766666".split('').map(x => parseInt(x)).sort();
// let items = "qwertwuxypoiuz".split('').sort();
//let items = "012346789".split('').map(x=> parseInt(x));
function binary_search(itemType, key, low, high) {
let middle = Math.floor((low + high) / 2);
if (low > high) {
return -1;
}
if (itemType[middle] == key) {
return middle;
}
if (itemType[middle] > key) {
return binary_search(itemType, key, low, middle - 1);
} else {
return binary_search(itemType, key, middle + 1, high);
}
}
function binary_search_high(itemType, key, low, high) {
let middle = Math.floor((low + high) / 2);
if (low > high) {
return high;
}
if (itemType[middle] > key) {
return binary_search_high(itemType, key, low, middle - 1);
} else {
return binary_search_high(itemType, key, middle + 1, high);
}
}
function binary_search_low(itemType, key, low, high) {
let middle = Math.floor((low + high) / 2);
if (low > high) {
return low;
}
if (itemType[middle] < key) {
return binary_search_low(itemType, key, middle + 1, high);
} else {
return binary_search_low(itemType, key, low, middle - 1);
}
}
console.log(items.map((s, idx) => `${idx}-${s}`));
const key = 'u'
console.log(`search item : ${key}`);
//let idx = binary_search(items, key, 0, items.length);
//console.log(`search index: ${idx}`);
let low = binary_search_low(items, key, 0, items.length);
let high = binary_search_high(items, key, 0, items.length);
console.log(`range: ${low} -- ${high}`);