-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathbinarySearchST.js
72 lines (62 loc) · 1.51 KB
/
binarySearchST.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
console.log('binarylSearchST:')
/* input start */
var input = require('../../../generator/index').getRandomNumbers();
/* input end */
console.log('> input: ' + input);
// binarylSearchST
function binarylSearchST() {
var keys = [], vals = [];
return {
keys: keys,
vals: vals,
put: function(key, val) {
var pos = this.rank(key);
var N = keys.length;
if(pos == 0) {
keys[0] = key;
vals[0] = val;
}
if(pos < N && keys[pos] === key) {
vals[pos] = val;
return;
}
for(var i = N; i >= pos + 1; i--) {
keys[i + 1] = keys[i];
vals[i + 1] = vals[i];
}
keys[i] = key;
vals[i] = val;
},
get: function(key) {
var pos = this.rank(key);
if(pos >= 0) {
return {
key: keys[pos],
val: vals[pos]
}
}
return -1;
},
rank: function(key) {
var start = 0, end = Math.max(keys.length - 1, 0), mid;
while(start < end) {
mid = ((end - start) >> 1) + start;
if(!keys[mid]) return mid;
if(keys[mid] < key) end = mid - 1;
else if (keys[mid] > key) start = mid + 1;
return mid;
}
return start;
}
}
}
var st = new binarylSearchST();
'www.barretlee.com'.split('').forEach(function(item, index){
st.put(item, index);
});
console.log(st.keys.join(', '));
console.log(st.vals.join(', '));
console.log(st.get('l'));
/* output start */
console.log('> output: ' + binarylSearchST(input));
/* output end */