Jump Search - GeeksforGeeks

18 Feb, 2022
Like Binary Search, Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.For example, suppose we have an array arr[] of size n and block (to be jumped) size m. Then we search at the indexes arr[0], arr[m], arr[2m].....arr[km] and so on. Once we find the interval (arr[km] < x < arr[(k+1)m]), we perform a linear search operation from the index km to find the element x.Let’s consider the following array: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610). The length of the array is 16. Jump search will find the value of 55 with the following steps assuming that the block size to be jumped is 4. STEP 1: Jump from index 0 to index 4; STEP 2: Jump from index 4 to index 8; STEP 3: Jump from index 8 to index 12; STEP 4: Since the element at index 12 is greater than 55 we will jump back a step to come to index 8. STEP 5: Perform a linear search from index 8 to get the element 55.What is the optimal block size to be skipped? In the worst case, we have to do n/m jumps and if the last checked value is greater than the element to be searched for, we perform m-1 comparisons more for linear search. Therefore the total number of comparisons in the worst case will be ((n/m) + m-1). The value of the function ((n/m) + m-1) will be minimum when m = √n. Therefore, the best step size is m = √n. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to implement Jump Search #include <bits/stdc++.h>using namespace std; int jumpSearch(int arr[], int x, int n){    // Finding block size to be jumped    int step = sqrt(n);     // Finding the block where element is    // present (if it is present)    int prev = 0;    while (arr[min(step, n)-1] < x)    {        prev = step;        step += sqrt(n);        if (prev >= n)            return -1;    }     // Doing a linear search for x in block    // beginning with prev.    while (arr[prev] < x)    {        prev++;         // If we reached next block or end of        // array, element is not present.        if (prev == min(step, n))            return -1;    }    // If element is found    if (arr[prev] == x)        return prev;     return -1;} // Driver program to test functionint main(){    int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,                34, 55, 89, 144, 233, 377, 610 };    int x = 55;    int n = sizeof(arr) / sizeof(arr[0]);         // Find the index of 'x' using Jump Search    int index = jumpSearch(arr, x, n);     // Print the index where 'x' is located    cout << "\nNumber " << x << " is at index " << index;    return 0;} // Contributed by nuclode
// Java program to implement Jump Search.public class JumpSearch{    public static int jumpSearch(int[] arr, int x)    {        int n = arr.length;         // Finding block size to be jumped        int step = (int)Math.floor(Math.sqrt(n));         // Finding the block where element is        // present (if it is present)        int prev = 0;        while (arr[Math.min(step, n)-1] < x)        {            prev = step;            step += (int)Math.floor(Math.sqrt(n));            if (prev >= n)                return -1;        }         // Doing a linear search for x in block        // beginning with prev.        while (arr[prev] < x)        {            prev++;             // If we reached next block or end of            // array, element is not present.            if (prev == Math.min(step, n))                return -1;        }         // If element is found        if (arr[prev] == x)            return prev;         return -1;    }     // Driver program to test function    public static void main(String [ ] args)    {        int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,                    34, 55, 89, 144, 233, 377, 610};        int x = 55;         // Find the index of 'x' using Jump Search        int index = jumpSearch(arr, x);         // Print the index where 'x' is located        System.out.println("\nNumber " + x +                            " is at index " + index);    }}
# Python3 code to implement Jump Searchimport math def jumpSearch( arr , x , n ):         # Finding block size to be jumped    step = math.sqrt(n)         # Finding the block where element is    # present (if it is present)    prev = 0    while arr[int(min(step, n)-1)] < x:        prev = step        step += math.sqrt(n)        if prev >= n:            return -1         # Doing a linear search for x in    # block beginning with prev.    while arr[int(prev)] < x:        prev += 1                 # If we reached next block or end        # of array, element is not present.        if prev == min(step, n):            return -1         # If element is found    if arr[int(prev)] == x:        return prev         return -1 # Driver code to test functionarr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21,    34, 55, 89, 144, 233, 377, 610 ]x = 55n = len(arr) # Find the index of 'x' using Jump Searchindex = jumpSearch(arr, x, n) # Print the index where 'x' is locatedprint("Number" , x, "is at index" ,"%.0f"%index) # This code is contributed by "Sharad_Bhardwaj".
// C# program to implement Jump Search.using System;public class JumpSearch{    public static int jumpSearch(int[] arr, int x)    {        int n = arr.Length;         // Finding block size to be jumped        int step = (int)Math.Sqrt(n);         // Finding the block where element is        // present (if it is present)        int prev = 0;        while (arr[Math.Min(step, n)-1] < x)        {            prev = step;            step += (int)Math.Sqrt(n);            if (prev >= n)                return -1;        }         // Doing a linear search for x in block        // beginning with prev.        while (arr[prev] < x)        {            prev++;             // If we reached next block or end of            // array, element is not present.            if (prev == Math.Min(step, n))                return -1;        }         // If element is found        if (arr[prev] == x)            return prev;         return -1;    }     // Driver program to test function    public static void Main()    {        int[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21,                    34, 55, 89, 144, 233, 377, 610};        int x = 55;         // Find the index of 'x' using Jump Search        int index = jumpSearch(arr, x);         // Print the index where 'x' is located        Console.Write("Number " + x +                            " is at index " + index);    }}
<?php// PHP program to implement Jump Search function jumpSearch($arr, $x, $n){    // Finding block size to be jumped    $step = sqrt($n);     // Finding the block where element is    // present (if it is present)    $prev = 0;    while ($arr[min($step, $n)-1] < $x)    {        $prev = $step;        $step += sqrt($n);        if ($prev >= $n)            return -1;    }     // Doing a linear search for x in block    // beginning with prev.    while ($arr[$prev] < $x)    {        $prev++;         // If we reached next block or end of        // array, element is not present.        if ($prev == min($step, $n))            return -1;    }    // If element is found    if ($arr[$prev] == $x)        return $prev;     return -1;} // Driver program to test function$arr = array( 0, 1, 1, 2, 3, 5, 8, 13, 21,                34, 55, 89, 144, 233, 377, 610 );$x = 55;$n = sizeof($arr) / sizeof($arr[0]);     // Find the index of '$x' using Jump Search$index = jumpSearch($arr, $x, $n); // Print the index where '$x' is locatedecho "Number ".$x." is at index " .$index;return 0;?>
<script>// Javascript program to implement Jump Search function jumpSearch(arr, x, n){    // Finding block size to be jumped    let step = Math.sqrt(n);       // Finding the block where element is    // present (if it is present)    let prev = 0;    while (arr[Math.min(step, n)-1] < x)    {        prev = step;        step += Math.sqrt(n);        if (prev >= n)            return -1;    }       // Doing a linear search for x in block    // beginning with prev.    while (arr[prev] < x)    {        prev++;           // If we reached next block or end of        // array, element is not present.        if (prev == Math.min(step, n))            return -1;    }    // If element is found    if (arr[prev] == x)        return prev;       return -1;} // Driver program to test functionlet arr = [0, 1, 1, 2, 3, 5, 8, 13, 21,                34, 55, 89, 144, 233, 377, 610];let x = 55;let n = arr.length;       // Find the index of 'x' using Jump Searchlet index = jumpSearch(arr, x, n);   // Print the index where 'x' is locateddocument.write(`Number ${x} is at index ${index}`);   // This code is contributed by _saurabh_jaiswal</script>
Output:  
Number 55 is at index 10
Time Complexity : O(√n) Auxiliary Space : O(1)Important points:  
Works only sorted arrays.
The optimal size of a block to be jumped is (√ n). This makes the time complexity of Jump Search O(√ n).
The time complexity of Jump Search is between Linear Search ( ( O(n) ) and Binary Search ( O (Log n) ).
Binary Search is better than Jump Search, but Jump search has an advantage that we traverse back only once (Binary Search may require up to O(Log n) jumps, consider a situation where the element to be searched is the smallest element or just bigger than the smallest). So in a system where binary search is costly, we use Jump Search.
 
YouTubeGeeksforGeeks506K subscribersJump Search | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=63kS6ZkMpkA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: https://en.wikipedia.org/wiki/Jump_searchThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
sahirDO3
aryan613
jigyansu
_saurabh_jaiswal
nipul1
2dmahgxu28nbib04rccrydls8oakhp6506570a0w
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
Most frequent element in an array
Best First Search (Informed Search)
Quickselect Algorithm
Find the missing and repeating number
Find a peak element
Complexity Analysis of Binary Search