Skip to content

Commit 0de1181

Browse files
committed
Add jump search algorithm
1 parent d97ffda commit 0de1181

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

algorithms/Searching/jump_search.m

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
function found_at = jump_search(arr, value)
2+
% Contributed by - Harshit Pant, harshitpant83@gmail.com
3+
4+
% arr - The input array, should be sorted in ascending order.
5+
% 'arr' can contain -ve numbers as well as non-integers.
6+
% value - The value to be searched in the array.
7+
% found_at - The index at which 'value' is found in 'arr'.
8+
% -1 is returned if 'value' is not found in 'arr'.
9+
10+
n = length(arr);
11+
12+
% 'm' holds the block size
13+
m = sqrt(n);
14+
m = round(m);
15+
low = 1;
16+
high = 1 + m;
17+
18+
found_at = -1;
19+
20+
while arr(min(high, n)) < value
21+
low = high;
22+
high = high + m;
23+
if low >= n
24+
return;
25+
endif;
26+
endwhile;
27+
28+
while arr(low) < value
29+
low = low + 1;
30+
if low > min(high, n)
31+
return;
32+
endif;
33+
endwhile;
34+
35+
if arr(low) == value
36+
found_at = low;
37+
endif;
38+
39+
endfunction;
40+
41+
42+
% TEST:
43+
% Save this file to your local computer, then use the command:
44+
% jump_search([-11.1, -3.3, -1.3, 0.1, 1.5, 3.5, 3.9, 5.5, 7.5, 9.6, 13.7, 21.3, 35.9], 7.5)
45+
% This should return, ans = 9.
46+
% TODO - Transfer this test when automated testing functionality is added to this repository.

0 commit comments

Comments
 (0)