I’m trying to implement a binary search algorithm in JavaScript. Things seem okay, but my return statements appear to be returning undefined. Can anybody tell me what’s wrong here?
Fiddle: http://jsfiddle.net/2mBdL/
JavaScript
x
40
40
1
var a = [
2
1,
3
2,
4
4,
5
6,
6
1,
7
100,
8
0,
9
10000,
10
3
11
];
12
13
a.sort(function (a, b) {
14
return a - b;
15
});
16
17
console.log('a,', a);
18
19
function binarySearch(arr, i) {
20
var mid = Math.floor(arr.length / 2);
21
console.log(arr[mid], i);
22
23
if (arr[mid] === i) {
24
console.log('match', arr[mid], i);
25
return arr[mid];
26
} else if (arr[mid] < i && arr.length > 1) {
27
console.log('mid lower', arr[mid], i);
28
binarySearch(arr.splice(mid, Number.MAX_VALUE), i);
29
} else if (arr[mid] > i && arr.length > 1) {
30
console.log('mid higher', arr[mid], i);
31
binarySearch(arr.splice(0, mid), i);
32
} else {
33
console.log('not here', i);
34
return -1;
35
}
36
37
}
38
var result = binarySearch(a, 100);
39
console.log(result);
40
Advertisement
Answer
You’re not explicitly returning the recursive inner calls (i.e. return binarySearch()
), so the call stack unfolds with no return value. Update your code like so:
JavaScript
1
13
13
1
// ...
2
if (arr[mid] === i) {
3
console.log('match', arr[mid], i);
4
return arr[mid];
5
} else if (arr[mid] < i && arr.length > 1) {
6
console.log('mid lower', arr[mid], i);
7
return binarySearch(arr.splice(mid, Number.MAX_VALUE), i);
8
} else if (arr[mid] > i && arr.length > 1) {
9
console.log('mid higher', arr[mid], i);
10
return binarySearch(arr.splice(0, mid), i);
11
} else {
12
// ...
13
See a working fiddle