forked from kolodny/exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (43 loc) · 1.05 KB
/
index.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
function searchB(arr,elem
, start /*optional start position*/
, end /*optional end position*/){
var index = -1;
start = start || 0;
end = end || arr.length,
length = end-start;
if(length === 1 && elem === arr[start]){
index = start;
}else if(length > 1){
var half = Math.round(length / 2),
middle = start+half;
if(arr[middle] === elem){
return middle;
}else if(elem < arr[middle]){
index = searchB(arr,elem,start,middle);
}else{
index = searchB(arr,elem,middle,end);
}
}
return index;
}
function searchNoOptimization(arr,elem
, start /*optional start position*/
, end /*optional end position*/){
var index = -1;
start = start || 0;
end = end || arr.length,
length = end-start;
if(length === 1 && elem === arr[start]){
index = start;
}else if(length > 1){
var half = Math.round(length / 2),
middle = start+half;
if(elem < arr[middle]){
index = searchNoOptimization(arr,elem,start,middle);
}else{
index = searchNoOptimization(arr,elem,middle,end);
}
}
return index;
}
module.exports = searchNoOptimization;