Jump Search in Python (2024)

Introduction

Finding the right data we need is an age-old problem before computers. As developers, we create many search algorithms to retrieve data efficiently.

Search algorithms can be divided into two broad categories: sequential and interval searches. Sequential searches check each element in a data structure. Interval searches check various points of the data (called intervals), reducing the time it takes to find an item, given a sorted dataset.

In this article, you will cover Jump Search in Python - a hybrid combination of sequential search and interval search on sorted arrays.

Jump Search

With Jump Search, the sorted array of data is split into subsets of elements called blocks. We find the search key (input value) by comparing the search candidate in each block. As the array is sorted, the search candidate is the highest value of a block.

When comparing the search key to a search candidate, the algorithm can then do 1 of 3 things:

  1. If the search candidate is lesser than the search key, we'll check the subsequent block
  2. If the search candidate is greater than the search key, we'll do a linear search on the current block
  3. If the search candidate is the same as the search key, return the candidate

The size of the block is chosen as the square root of the array's length. Therefore, arrays with length n have a block size of √n, as this on average gives the best performance for most arrays.

It might be useful to illustrate how it works. Here's how Jump Search would find the value 78 in an array of 9 elements:

The above example finds the element in 5 steps, as there are two checks in the linear search section.

Now that we have a high-level appreciation for how it works, let's look at a pseudocode implementation of the algorithm.

Jump Search Steps

Inputs:

  • Array/list A of size n
  • Search Key item

Output:

  • Index of the matched Search Key or -1 if the item is not found

Steps

  • Step 1: Find the length of the sorted source list - n = len(A)
  • Step 2: Determine the suitable Block Size - m = √n
  • Step 3: Iteration begins at the index of the item at i = 0 with a step of m and continues until the window reaches the end of the list.
  • Step 4: Compare A[i+m] (i+m is the last index of a block) and the item
    • a) If A[i+m] == item, Return i+m; Code Exits
    • b) If A[i+m] > item, Proceed to the linear search inside the block known as derived list B = A[i: i+m]
      • Iterate and compare each element of the list with the search key and return the matching i if found; Code Exits
    • c) If A[i+m] < item, Proceed with the next iteration to Step 4 :arrows_clockwise:
  • Step 5: Iterate the elements of the list that don't fit in the block and return the matching index i. If no matches were found, return -1; Code Exits

As we now understand how it works, let us implement this algorithm in Python!

Implementation

Knowing how Jump Search works, let's go ahead and implement it in Python:

'''Jump Search functionArguments:A - The source listitem - Element for which the index needs to be found'''import mathdef jump_search(A, item): print("Entering Jump Search") n = len(A) # Length of the array m = int(math.sqrt(n)) # Step length i = 0 # Starting interval while i != len(A)-1 and A[i] < item: print("Processing Block - {}".format(A[i: i+m])) if A[i+m-1] == item: # Found the search key return i+m-1 elif A[i+m-1] > item: # Linear search for key in block B = A[i: i+m-1] return linear_search(B, item, i) i += m B = A[i:i+m] # Step 5 print("Processing Block - {}".format(B)) return linear_search(B, item, i)

The jump_search() function takes two arguments - the sorted list under evaluation as the first argument and the element that needs to be found in the second argument. The math.sqrt() function is used to find the block size. The iteration is facilitated by a while condition and the increment is made feasible by the incremented i += m.

You would have noticed that the Step 4b and Step 5 have a linear_search() function invoked. The linear_search() function is triggered in one of the following scenarios.

  • Step 4b - When there's a shift in comparison. If the last element of a block/window is greater than the item, the linear_search() is triggered.

  • Step 5 - The remaining elements of the source list A that don't fit in a block are passed as a derived list to the linear_search() function.

The linear_search() function can be written like this:

'''Linear Search functionArguments:B - The derived listitem - Element for which the index needs to be foundloc - The Index where the remaining block begins'''def linear_search(B, item, loc): print("\t Entering Linear Search") i = 0 while i != len(B): if B[i] == item: return loc+i i += 1 return -1

In step 5, the remaining elements of the original list are passed to the linear_search() function as a derived list. The comparison is done against each element of the derived list B.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The matched index of the derived list is added to the index of the source block, to provide the exact index position of the element in the source list. If there are no matches found, we return -1 to indicate that item was not found.

The complete snippet can be found on <a rel=”nofollow noopener” href="https://github.com/StackAbuse/search-algorithms" target="_blank">GitHub.

Benchmarking - Jump Search vs Linear Search

The runtime for the Jump Search can be benchmarked against Linear Search. The following visualization illustrates how the algorithms perform while searching for an element near the end of a sorted array. The shorter the bar, the better:

As the number of elements in the list increases, Jump Search is quicker than the Linear Search algorithm.

Big-O Analysis

Let's do a more general analysis of how Jump Search performs. We'll once again consider the worst-case scenario where the element to be found is at the end of the list.

For a list of n elements and a block size of m, Jump Search would ideally perform n/m jumps. Considering the block size to be √n, the runtime too would be O(√n).

This puts Jump Search in between Linear Search (worst) with a runtime complexity of O(n) and Binary Search (best) with a runtime complexity of O(log n). Hence, Jump Search can be used in places where the binary search is not feasible and linear search is too costly.

Conclusion

In this article, we have covered the basics of the Jump Search algorithm. We then examined how Jump Search works with pseudocode before implementing it in Python. Thereafter, we analyzed how Jump Search performs, as well as its theoretical speed bounds.

Jump Search in Python (2024)

FAQs

What is a jump search in Python? ›

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.

How to do jump search? ›

Jump Search Algorithm Explained
  1. Define the value of k, the number of jump: Optimal jump size is √N where the N is the length of array.
  2. Jump the array k-by-k searching by the condition Array[i] < valueWanted < Array[i+k]
  3. Do a linear search between Array[i] and Array[i + k]
Jan 12, 2020

Is jump search better than binary search? ›

Jump search is a search algorithm for sorted lists which runs in O(√n) time, but has the advantage of only making backwards steps at the end (and given the ability to make arbitrarily long backwards steps, guarantees only a single backwards step); thus, it may be preferable to binary search if reverse traversal is ...

What is the difference between linear search and jump search? ›

Jump search has better execution than linear search for large sorted lists. It has a time complexity of O(sqrt(n)), where n is the number of elements in the list. Jump search is simple and easy to implement.

How does jump search work? ›

The Jump Search algorithm works by initially skipping to the next block of elements and only performing a linear search if the target element is within the range of the previous block. It uses the principle that a sorted array allows for faster searching by skipping over multiple elements.

Why do we use jump statement in Python? ›

Jump statements can be used to modify the behavior of conditional and iterative statements. Jump statements allow you to exit a loop, start the next iteration of a loop, or explicitly transfer program control to a specified location in your program.

Does jump search need to be sorted? ›

Basic principles

Jump search is an algorithm designed for efficiently searching in sorted arrays, whether they are in ascending or descending order.

What are jump commands? ›

The Jump command is used to branch to another page within the current script. The branching commands feature options to make branching conditional. Lightwing branches only if all of the defined conditions are true, otherwise execution continues with the next consecutive page in the current script.

What is the best case of jump search? ›

Explanation: Best case of jump search will be when the first element of the array is the element that is being searched. In this case only one comparison will be required. Thus it will have a time complexity of O(1).

When to use jump search over binary search? ›

It has a time complexity of O(√n), which is more efficient than linear search but less efficient than binary search. Jump search is useful when the dataset is large and the overhead of binary search's recursive calls is significant.

How can jump search be improved? ›

How can Jump Search be improved?
  1. A. Start searching from the end.
  2. B. Begin from the kth item, where k is the step size.
  3. C. Cannot be improved.
  4. D. Step size should be other than sqrt(n)
Jan 9, 2020

What is faster than binary search? ›

Hashing. For implementing associative arrays, hash tables, a data structure that maps keys to records using a hash function, are generally faster than binary search on a sorted array of records. Most hash table implementations require only amortized constant time on average.

What are the advantages of jump search? ›

This is better than a linear search, but worse than a binary search. The advantage over the latter is that a jump search only needs to jump backwards once, while a binary can jump backwards up to log n times. This can be important if jumping backwards takes significantly more time than jumping forward.

What is the ideal block size for jump search? ›

Save this question. The value of the function ((n/m) + m-1) will be minimum when m = √n . Therefore, the best step size is m = √n . Here, n is size of array and m is block size to be jumped.

What is the primary advantage of jump search over linear search? ›

The fundamental idea behind this searching technique is to search fewer number of elements compared to linear search algorithm (which scans every element in the array to check if it matches with the element being searched or not).

What is JuMP in coding? ›

JuMP is a modeling language and collection of supporting packages for mathematical optimization in Julia. JuMP makes it easy to formulate and solve a range of problem classes, including linear programs, integer programs, conic programs, semidefinite programs, and constrained nonlinear programs.

What does search () do in Python? ›

The search() function searches the string for a match, and returns a Match object if there is a match.

Does JuMP search need to be sorted? ›

Basic principles

Jump search is an algorithm designed for efficiently searching in sorted arrays, whether they are in ascending or descending order.

How many JuMP statements are there in Python? ›

There are three types of jump statements used in python. It is used to skip all the remaining statements in the loop and move controls back to the top of the loop. This statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5326

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.