JavaScript Jump Search<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JavaScript Jump Search

Posted on: June 20, 2017

The Jump Search algorithm allows to combine a linear search with a speed optimization. This mean that instead of going 1 by 1, we will increase the step of √n and increase that step of √n which make the step getting bigger and bigger.

The asymptotic analysis of Jump Search is o(√n). Like the binary search, it needs to be sorted. The advantage against binary search is that Jump Search traversed back only once.

1var arrayToSearch = [2, 6, 8, 12, 43, 78, 99, 134, 144, 156, 199, 256, 500];
2
3console.log("Found at position :" + jumpSearch(arrayToSearch, 2));
4console.log("Found at position :" + jumpSearch(arrayToSearch, 256));
5console.log("Found at position :" + jumpSearch(arrayToSearch, 500));
6console.log("Found at position :" + jumpSearch(arrayToSearch, 44444));
7
8function jumpSearch(arrayToSearch, valueToSearch) {
9 var length = arrayToSearch.length;
10 var step = Math.floor(Math.sqrt(length));
11 var index = Math.min(step, length) - 1;
12 var lowerBound = 0;
13 while (arrayToSearch[Math.min(step, length) - 1] < valueToSearch) {
14 lowerBound = step;
15 step += step;
16 if (lowerBound >= length) {
17 return -1;
18 }
19 }
20 var upperBound = Math.min(step, length);
21 while (arrayToSearch[lowerBound] < valueToSearch) {
22 lowerBound++;
23 if (lowerBound == upperBound) {
24 return -1;
25 }
26 }
27 if (arrayToSearch[lowerBound] == valueToSearch) {
28 return lowerBound;
29 }
30 return -1;
31}

It requires two loops. The first loop looks at value to determine if the value is under or not the jump. This one will set the lower bound variable that contains the lower bound of the linear search. The second loop does the linear from the lower bound to the upper bound. The upper bound can be the end of the array, or if a step.