-
Notifications
You must be signed in to change notification settings - Fork 321
Expand file tree
/
Copy pathq05.js
More file actions
34 lines (30 loc) · 925 Bytes
/
q05.js
File metadata and controls
34 lines (30 loc) · 925 Bytes
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
/*10.5 Sparse Search: Given a sorted array of strings that is interspersed
with empty strings, write a method to find the location of a given string.*/
export function findIndex(stringArray, word) {
//saving word indexes in separate array
let wordIndexes = [];
for (let i = 0, len = stringArray.length; i < len; i++) {
if (stringArray[i] !== '') {
wordIndexes.push(i);
}
}
//doing binary search only with indexes of words
let left = 0;
let right = wordIndexes.length - 1;
while (left !== right) {
if (word === stringArray[wordIndexes[left]]) {
return wordIndexes[left];
}
if (word === stringArray[wordIndexes[right]]) {
return wordIndexes[right];
}
const middle = Math.floor(left + (right - left) / 2);
if (word <= stringArray[wordIndexes[middle]] || middle === left) {
right = middle;
}
else {
left = middle;
}
}
return -1;
}