Search a sorted array by jumping in fixed steps, then performing a linear scan within a block.
Jump search finds a target in a sorted array by skipping ahead in fixed-size steps and then performing a linear scan within a small block. It reduces the number of comparisons compared to linear search while avoiding full binary search.
Problem
Given a sorted array of length and a value , find an index such that
If no such index exists, return .
Key Idea
Instead of checking every element, jump forward by a fixed step size :
- Check
- Stop when or the end is reached
- Perform linear search in the previous block
Optimal step size:
This balances the number of jumps and the size of the final scan.
Algorithm
jump_search(A, x):
n = length(A)
k = floor(sqrt(n))
prev = 0
curr = 0
while curr < n and A[curr] < x:
prev = curr
curr = curr + k
curr = min(curr, n - 1)
for i from prev to curr:
if A[i] == x:
return i
return -1Example
Let
and
Step size:
Jump phase:
| step | index | value |
|---|---|---|
| 1 | 0 | 2 |
| 2 | 3 | 8 |
| 3 | 6 | 14 |
Now the target lies in range . Linear scan finds index .
Correctness
The jump phase finds a block such that:
Since the array is sorted, if exists, it must lie within this block. The linear scan checks all elements in that block.
Complexity
Let be the step size.
| phase | cost |
|---|---|
| jumps | |
| linear scan |
Total:
Minimized when:
So:
Space:
Comparison
| method | requirement | time |
|---|---|---|
| linear search | none | |
| jump search | sorted | |
| binary search | sorted |
Jump search sits between linear and binary search.
When to Use
- Sorted arrays with expensive random access
- Situations where sequential access is cheaper
- Systems where memory access patterns matter
Notes
- Performs fewer comparisons than linear search
- Simpler than binary search
- Not optimal for very large datasets
Implementation
import math
def jump_search(a, x):
n = len(a)
k = int(math.sqrt(n))
prev = 0
curr = 0
while curr < n and a[curr] < x:
prev = curr
curr += k
curr = min(curr, n - 1)
for i in range(prev, curr + 1):
if a[i] == x:
return i
return -1import "math"
func JumpSearch(a []int, x int) int {
n := len(a)
k := int(math.Sqrt(float64(n)))
prev, curr := 0, 0
for curr < n && a[curr] < x {
prev = curr
curr += k
}
if curr >= n {
curr = n - 1
}
for i := prev; i <= curr; i++ {
if a[i] == x {
return i
}
}
return -1
}