easy +10 pts

Jump Search

Implement jump search to find an element in a sorted list efficiently.

Write a function `jump_search(arr, target)` that returns the index of `target` in the sorted list `arr` using the jump search algorithm. If `target` is not present, return `-1`. **Algorithm specification:** 1. Let `n = len(arr)`. Choose the block size `step = int(n ** 0.5)` (integer square root). If `n == 0`, return `-1`. 2. Start at index `prev = 0` and `curr = step`. While `curr < n` and `arr[curr] < target`, set `prev = curr`, `curr += step`. Stop when `curr >= n` or `arr[curr] >= target`. 3. Perform a linear search from `prev` to `min(curr, n-1)` inclusive. If `arr[i] == target` at some index `i`, return `i`. 4. If not found, return `-1`. Assume `arr` is sorted in non-decreasing order. The function must work for any list of comparable values (integers, floats, strings, etc).

Constraints

- `0 <= len(arr) <= 10^5` - Elements are comparable and sorted non-decreasingly. - The algorithm must run in O(√n) time and O(1) space.

Example

>>> jump_search([1, 3, 5, 7, 9], 5)
2
>>> jump_search([1, 3, 5, 7, 9], 6)
-1
>>> jump_search([], 10)
-1
>>> jump_search([10], 10)
0
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compute the block size as the integer square root of the array length.
Jump forward in steps while the current element is less than the target.
Linear scan within the chosen block to find the exact index.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.