Swift Program to Implement Jump Search

Swift Program to Implement Jump Search

Jump Search is one of those algorithms that feels simple once you understand the idea behind it, yet it offers a nice step up from basic searching techniques. In many ways, it sits between Linear Search and Binary Search, borrowing ideas from both. It keeps the data sorted like Binary Search does, but it moves through the array in blocks instead of halving it. Because of this structure, Jump Search becomes a great tool for learners who want to explore different strategies for searching while still working with easy-to-follow logic.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

The heart of Jump Search lies in reducing the number of comparisons. Instead of looking at every element in order, the algorithm makes jumps of a fixed size. When it detects that the target might be inside a certain block, it slows down and checks each value inside that block carefully. This makes Jump Search helpful when dealing with sorted arrays where you want something more efficient than a full scan but don’t want the complexity of deeper recursive search methods.

In the real world, Jump Search is not as commonly used as Binary Search, but it is still important in learning algorithm design. It teaches you how to balance speed and simplicity, and it shows how skipping ahead can save time without needing complex recursion. Many students find Jump Search to be a friendly stepping stone toward more advanced searching techniques.

Program 1: Basic Jump Search Using a Loop

This program shows the classic version of Jump Search using simple loops. It takes a sorted list of numbers and jumps through it using a fixed block size.

import Foundation

func jumpSearch(_ array: [Int], target: Int) -> Int? {

    let n = array.count
    let step = Int(sqrt(Double(n)))
    var prev = 0
    var current = step

    while current < n && array[current] < target {
        prev = current
        current += step
    }

    for i in prev..<min(current, n) {

        if array[i] == target {
            return i
        }

    }

    return nil

}

let data = [2, 5, 9, 14, 18, 23, 27, 31, 36]

if let index = jumpSearch(data, target: 23) {
    print("Found at index \(index)")
} else {
    print("Not found")
}

This version works by taking jumps of square-root size until it finds a block that may contain the target. Once the correct block is found, the program scans it linearly to locate the exact value. Beginners often appreciate this structure because everything is clear, predictable, and easy to trace on paper.

Program 2: Jump Search With a Custom Step Size

This example gives you more control by letting you choose your own step size instead of using the square-root default. It is useful when working with data that may need tuning.

import Foundation

func jumpSearchCustom(_ array: [Int], target: Int, stepSize: Int) -> Int? {

    let n = array.count
    var prev = 0
    var current = stepSize

    while current < n && array[current] < target {
        prev = current
        current += stepSize
    }

    for i in prev..<min(current, n) {

        if array[i] == target {
            return i
        }

    }

    return nil

}

let values = [3, 6, 11, 17, 22, 29, 35, 41]

if let index = jumpSearchCustom(values, target: 29, stepSize: 3) {
    print("Found at index \(index)")
} else {
    print("Not found")
}

This version is great for experimenting. By trying different step sizes, beginners can observe how performance changes. It helps learners understand why the square-root step size is normally chosen for efficiency.

Program 3: Recursive Jump Search

For learners who enjoy recursion, this program shows how to perform Jump Search without loops. It keeps the same logic but organizes the work through recursive calls.

import Foundation

func recursiveJumpSearch(_ array: [Int], target: Int, step: Int, prev: Int, current: Int) -> Int? {

    if prev >= array.count {
        return nil
    }

    if current >= array.count || array[current] >= target {

        for i in prev..<min(current, array.count) {

            if array[i] == target {
                return i
            }

        }

        return nil

    }

    return recursiveJumpSearch(array, target: target, step: step, prev: current, current: current + step)

}

let numbers = [1, 4, 8, 12, 19, 25, 30, 33, 40]
let s = Int(sqrt(Double(numbers.count)))

if let index = recursiveJumpSearch(numbers, target: 25, step: s, prev: 0, current: s) {
    print("Found at index \(index)")
} else {
    print("Not found")
}

This approach shows that Jump Search can be expressed in many styles. It is helpful for students practicing how to break a problem into smaller pieces. Even though recursion is not the usual way to write Jump Search, it offers a fresh perspective.

Program 4: Generic Jump Search for Any Comparable Type

This version makes the algorithm more flexible by allowing it to work with any type that conforms to Comparable. It can handle more than numbers, as long as the data is sorted.

import Foundation

func genericJumpSearch<T: Comparable>(_ array: [T], target: T) -> Int? {

    let n = array.count
    let step = Int(sqrt(Double(n)))
    var prev = 0
    var current = step

    while current < n && array[current] < target {
        prev = current
        current += step
    }

    for i in prev..<min(current, n) {

        if array[i] == target {
            return i
        }

    }

    return nil

}

let words = ["apple", "banana", "grape", "mango", "orange", "peach"]

if let index = genericJumpSearch(words, target: "mango") {
    print("Found at index \(index)")
} else {
    print("Not found")
}

Using generics makes the algorithm more reusable. Beginners can see how Swift’s type system helps create flexible code. It also shows that Jump Search is not limited to only numbers when designed the right way.

Program 5: Jump Search With Detailed Output

This version prints every jump and scan step. It is designed for learning and helps beginners follow the algorithm as it runs.

import Foundation

func jumpSearchTrace(_ array: [Int], target: Int) -> Int? {

    let n = array.count
    let step = Int(sqrt(Double(n)))
    var prev = 0
    var current = step

    while current < n && array[current] < target {

        print("Jumping to index \(current)")

        prev = current
        current += step

    }

    print("Scanning from \(prev) to \(min(current, n - 1))")

    for i in prev...min(current, n - 1) {

        print("Checking index \(i)")

        if array[i] == target {
            return i
        }

    }

    return nil

}

let items = [2, 4, 7, 10, 15, 20, 28, 32]

if let index = jumpSearchTrace(items, target: 15) {
    print("Found at index \(index)")
} else {
    print("Not found")
}

This program is very useful for beginners who want to visualize the algorithm. Seeing each step printed makes it easier to understand why Jump Search behaves the way it does and how the block jumps help speed things up.

Frequently Asked Questions (FAQ)

This section answers the most common questions new learners often ask about Jump Search and how it works in Swift.

Q1. Does Jump Search require sorted data?
Yes, Jump Search only works on sorted data. Without sorted values, the algorithm cannot safely skip ahead in blocks, and the jumps would not be meaningful.

Q2. Why does Jump Search use square-root steps?
The square root of the array size gives a good balance between the number of jumps and the length of the final linear scan. It is considered the most efficient block size for this method.

Q3. Is Jump Search faster than Binary Search?
Binary Search is usually faster because it cuts the search space in half each time. Jump Search can be easier to understand, but it rarely beats Binary Search in raw performance.

Q4. Can Jump Search be used with strings or custom types?
Yes, as long as the data is sorted and the type supports comparison. The generic example earlier shows how flexible the method can be.

Q5. Where is Jump Search used in real applications?
It is mostly used for teaching algorithm design. While not common in production systems, it helps students understand optimization and the idea of skipping ahead instead of checking everything.

Conclusion

Jump Search offers a simple yet interesting way to search through sorted data. It moves in steady jumps and then slows down when it reaches the block that might hold the answer. While it might not be the fastest technique compared to Binary Search, it is an excellent learning tool for beginners exploring search algorithms in Swift.

By practicing the different versions shown here, you can build confidence in understanding how search strategies work and learn how to write cleaner, more efficient code. Keep experimenting with different data sets and step sizes, and you will quickly become comfortable with this helpful algorithm.

Scroll to Top