-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathsearch-module.js
71 lines (66 loc) · 1.66 KB
/
search-module.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
(function (exports) {
const sequentialSearch = (dataStore, data) => {
for (var i = 0; i < dataStore.length; i++) {
if (dataStore[i] === data) {
return i
}
}
return -1
}
const binarySearch = (dataStore, data) => {
let upperBound = dataStore.length - 1
let lowerBound = 0
while (lowerBound <= upperBound) {
let mid = Math.floor((lowerBound + upperBound) / 2)
if (dataStore[mid] < data) {
lowerBound = mid + 1
} else if (dataStore[mid] > data) {
upperBound = mid - 1
} else {
return mid
}
}
return -1
}
const countOccurrences = (dataStore, data) => {
let count = 0
let position = binarySearch(dataStore, data)
if (position > -1) {
count += 1
for (let i = position; i > 0; i--) {
if (dataStore[i] === data) {
count += 1
} else {
break
}
}
for (let i = position + 1; i < dataStore.length; i++) {
if (dataStore[i] === data) {
count += 1
} else {
break
}
}
}
return count
}
const minValue = (dataStore) => {
let min = dataStore[0]
for (var i = 1; i < dataStore.length; i++) {
if (dataStore[i] < min) {
min = dataStore[i]
}
}
return min
}
const maxValue = (dataStore) => {
let max = dataStore[0]
for (var i = 1; i < dataStore.length; i++) {
if (dataStore[i] > max) {
max = dataStore[i]
}
}
return max
}
Object.assign(exports, {sequentialSearch, binarySearch, minValue, maxValue, countOccurrences})
}((typeof module.exports !== undefined) ? module.exports : window))