-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.js
89 lines (65 loc) · 1.63 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const Search = require("../Search")
class BinarySearch extends Search {
#keys
#values
#size
constructor() {
super()
this.#keys = []
this.#values = []
this.#size = 0
}
size() {
const size = this.#size
return size
}
isEmpty() {
const isEmpty = this.#size === 0
return isEmpty
}
get (key) {
const isEmpty = this.isEmpty()
if (isEmpty) {
return null
}
const rankedKey = this.rank(key)
const areKeysEqual = this.compareValues(this.#keys[rankedKey], key) === 0
if (rankedKey < this.#size && areKeysEqual) {
return this.#values[rankedKey]
} else {
return null
}
}
put (key, value) {
const rankedKey = this.rank(key)
const areKeysEqual = this.compareValues(this.#keys[rankedKey], key) === 0
if (rankedKey < this.#size && areKeysEqual) {
this.#values[rankedKey] = value
return
}
for (let size = this.#size; size > rankedKey; size--) {
this.#keys[size] = this.#keys[size - 1]
this.#values[size] = this.#values[size - 1]
}
this.#keys[rankedKey] = key
this.#values[rankedKey] = value
this.#size++
}
rank (key) {
let lowerIndex = 0
let higherIndex = this.#size - 1
while (lowerIndex <= higherIndex) {
const middleIndex = lowerIndex + Math.floor((higherIndex - lowerIndex) / 2)
const comparison = this.compareValues(key, this.#keys[middleIndex])
if (comparison < 0) {
higherIndex = middleIndex - 1
} else if (comparison > 0) {
lowerIndex = middleIndex + 1
} else {
return middleIndex
}
}
return lowerIndex
}
}
module.exports = BinarySearch