GoLang Program to Implement Jump Search

GoLang Program to Implement Jump Search

Searching efficiently is a key skill for any programmer, especially when dealing with large sorted arrays. While Linear Search checks each element one by one and Binary Search splits the array in halves, Jump Search offers a middle ground. It jumps ahead by fixed steps, reducing the number of comparisons, and then performs a linear search within the identified block.

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

Jump Search is particularly useful for sorted arrays where elements are uniformly distributed. The algorithm works by dividing the array into blocks of size roughly equal to the square root of the total array length. Once the block where the target may exist is found, a simple linear search inside that block locates the element. For beginners, Jump Search demonstrates the concept of block searching, which combines efficiency with simplicity.

Program 1: Iterative Jump Search

This program demonstrates the classic iterative Jump Search approach, which jumps in fixed intervals and then performs a linear search within the block.

package main

import (
    "fmt"
    "math"
)

func jumpSearch(arr []int, target int) int {

    n := len(arr)
    step := int(math.Sqrt(float64(n)))
    prev := 0

    for arr[min(step, n)-1] < target {

        prev = step
        step += int(math.Sqrt(float64(n)))

        if prev >= n {
            return -1
        }

    }

    for i := prev; i < min(step, n); i++ {

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

    }

    return -1

}

func min(a, b int) int {

    if a < b {
        return a
    }

    return b

}

func main() {

    numbers := []int{10, 20, 30, 40, 50, 60, 70, 80}
    target := 50
    index := jumpSearch(numbers, target)

    if index != -1 {
        fmt.Printf("Element %d found at index %d\n", target, index)
    } else {
        fmt.Printf("Element %d not found in the array\n", target)
    }

}

In this example, the algorithm jumps by sqrt(n) elements to find a block potentially containing the target. After locating the block, it performs a linear search. Beginners can see how combining jumping and linear searching makes the search faster than checking each element one by one.

Program 2: Jump Search with Step Printing

Sometimes it’s helpful to visualize each jump. This version prints the positions checked during jumps, making it easier to understand how the algorithm progresses.

package main

import (
    "fmt"
    "math"
)

func jumpSearchPrint(arr []int, target int) int {

    n := len(arr)
    step := int(math.Sqrt(float64(n)))
    prev := 0

    for arr[min(step, n)-1] < target {

        fmt.Printf("Jumping to index %d\n", min(step, n)-1)

        prev = step
        step += int(math.Sqrt(float64(n)))

        if prev >= n {
            return -1
        }

    }

    for i := prev; i < min(step, n); i++ {

        fmt.Printf("Checking index %d\n", i)

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

    }

    return -1

}

func min(a, b int) int {

    if a < b {
        return a
    }

    return b

}

func main() {

    numbers := []int{5, 15, 25, 35, 45, 55, 65, 75}
    target := 35
    index := jumpSearchPrint(numbers, target)

    if index != -1 {
        fmt.Printf("Element %d found at index %d\n", target, index)
    } else {
        fmt.Printf("Element %d not found in the array\n", target)
    }

}

By printing each jump and linear check, beginners can follow the algorithm visually and understand why the combination of jumps and linear search speeds up finding elements in sorted arrays.

Program 3: Recursive Jump Search

Although Jump Search is usually iterative, recursion can also be applied. This program demonstrates a recursive approach, which can help beginners practice thinking recursively.

package main

import (
    "fmt"
    "math"
)

func jumpSearchRec(arr []int, target int, prev int) int {

    n := len(arr)
    step := int(math.Sqrt(float64(n)))

    if prev >= n {
        return -1
    }

    if arr[min(prev+step, n)-1] < target {

        return jumpSearchRec(arr, target, prev+step)

    }

    for i := prev; i < min(prev+step, n); i++ {

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

    }

    return -1

}

func min(a, b int) int {

    if a < b {
        return a
    }

    return b

}

func main() {

    numbers := []int{10, 20, 30, 40, 50, 60, 70, 80}
    target := 60
    index := jumpSearchRec(numbers, target, 0)

    if index != -1 {
        fmt.Printf("Element %d found at index %d\n", target, index)
    } else {
        fmt.Printf("Element %d not found in the array\n", target)
    }

}

The recursive approach divides the array into blocks and calls itself on the next block until it finds the target. This teaches beginners how recursion can be combined with arithmetic-based searching to solve problems elegantly.

Program 4: Jump Search with Multiple Occurrences

In cases where an element may appear multiple times, it’s helpful to find all positions. This program extends Jump Search to handle multiple occurrences.

package main

import (
    "fmt"
    "math"
)

func jumpSearchAll(arr []int, target int) []int {

    indices := []int{}
    index := jumpSearch(arr, target)

    if index == -1 {
        return indices
    }

    // Check left side
    left := index - 1
    for left >= 0 && arr[left] == target {

        indices = append([]int{left}, indices...)
        left--

    }

    // Add middle index
    indices = append(indices, index)

    // Check right side
    right := index + 1

    for right < len(arr) && arr[right] == target {

        indices = append(indices, right)
        right++

    }

    return indices

}

func jumpSearch(arr []int, target int) int {

    n := len(arr)
    step := int(math.Sqrt(float64(n)))
    prev := 0

    for arr[min(step, n)-1] < target {

        prev = step
        step += int(math.Sqrt(float64(n)))

        if prev >= n {
            return -1
        }

    }

    for i := prev; i < min(step, n); i++ {

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

    }

    return -1

}

func min(a, b int) int {

    if a < b {
        return a
    }

    return b

}

func main() {

    numbers := []int{10, 20, 20, 20, 30, 40, 50}
    target := 20
    indices := jumpSearchAll(numbers, target)

    if len(indices) > 0 {
        fmt.Printf("Element %d found at indices %v\n", target, indices)
    } else {
        fmt.Printf("Element %d not found in the array\n", target)
    }

}

This program first finds one occurrence of the target and then expands to find all duplicates. It’s practical for real-world datasets where repeated values occur frequently.

Frequently Asked Questions (FAQ)

Jump Search is simpler than it may first appear. Here are answers to common questions:

Q1: What is Jump Search?
Jump Search is a search algorithm for sorted arrays that jumps ahead by fixed intervals and performs a linear search within a block.

Q2: How is it different from Binary Search?
Binary Search splits the array in halves every time, while Jump Search moves in fixed steps and only searches linearly in the identified block.

Q3: What is the time complexity of Jump Search?
Jump Search has a time complexity of O(√n), making it faster than Linear Search for large sorted arrays.

Q4: When should I use Jump Search?
It is most useful when the array is sorted and uniform, and when you want a simple search method faster than Linear Search.

Q5: Can Jump Search handle duplicate elements?
Yes, with slight modifications, Jump Search can locate all occurrences of a target element.

Conclusion

Jump Search is an elegant, efficient algorithm for searching sorted arrays. By combining block jumps and linear searches, it offers a practical improvement over Linear Search and an intuitive alternative to Binary Search. Beginners can start with the iterative approach, explore recursion, and adapt the algorithm to handle duplicates.

Practicing Jump Search in GoLang helps solidify understanding of search optimization, block-based algorithms, and arithmetic-based indexing. Once comfortable, you can apply similar strategies to more advanced searching techniques.

Scroll to Top