1
+ /**
2
+ * @function jumpSearch
3
+ * @description Jump search algorithm for a sorted array.
4
+ *
5
+ * Jump search is a searching algorithm for sorted arrays that checks elements
6
+ * by jumping ahead by fixed steps. The optimal step size is the square root of the array length.
7
+ *
8
+ * The algorithm works as follows:
9
+ * 1.Start from the first element and jump by step size until finding an element that is greater than or equal to the target value.
10
+ * 2.Go back one step and perform a linear search from there until finding the target value or reaching the end of the subarray.
11
+ * 3.If the target value is found, return its index. Otherwise, return -1 to indicate that it is not in the array.
12
+ *
13
+ * @param {number[] } array - sorted list of numbers
14
+ * @param {number } target - target number to search for
15
+ * @return {number } - index of the target number in the list, or -1 if not found
16
+ * @see [JumpSearch](https://www.geeksforgeeks.org/jump-search/)
17
+ * @example jumpSearch([1,2,3], 2) => 1
18
+ * @example jumpSearch([4,5,6], 2) => -1
19
+ */
20
+
21
+ export const jumpSearch = ( array : number [ ] , target : number ) : number => {
22
+ if ( array . length === 0 ) return - 1 ;
23
+
24
+ // declare pointers for the current and next indexes and step size
25
+ let currentIdx : number = 0 ,
26
+ stepSize : number = Math . floor ( Math . sqrt ( array . length ) ) ,
27
+ nextIdx : number = stepSize ;
28
+
29
+ while ( array [ nextIdx - 1 ] < target ) {
30
+ currentIdx = nextIdx ;
31
+ nextIdx += stepSize ;
32
+
33
+ if ( nextIdx >= array . length ) {
34
+ nextIdx = array . length - 1 ;
35
+ break ;
36
+ }
37
+ }
38
+
39
+ for ( let index = currentIdx ; index < nextIdx ; index ++ ) {
40
+ if ( array [ index ] == target )
41
+ {
42
+ return index ;
43
+ }
44
+ }
45
+
46
+ return - 1 ;
47
+ }
0 commit comments