GoLang Program to Implement Linear Search

GoLang Program to Implement Linear Search

Searching is one of the fundamental tasks in programming. Whenever you want to find a specific item in a collection of data, you need a search algorithm. Linear Search is the simplest and most straightforward method to find an element. It checks each element in the list, one by one, until it finds a match or reaches the end of the collection.

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

Linear Search is very useful for beginners because it’s easy to understand and implement. While it may not be the fastest search algorithm for large datasets, it works with both sorted and unsorted arrays, making it versatile. Learning Linear Search is a great starting point before moving on to more advanced techniques like Binary Search.

Program 1: Basic Linear Search Using Loop

This first program demonstrates a simple linear search using a for loop. It searches through an array of integers and returns the position of the target value.

package main

import "fmt"

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

    for i, value := range arr {

        if value == target {
            return i
        }

    }

    return -1

}

func main() {

    numbers := []int{10, 20, 30, 40, 50}
    target := 30
    index := linearSearch(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)
    }

}

This program works by looping through each element of the array. If the element matches the target, it returns the index. If the loop finishes without finding the target, it returns -1. Beginners can understand how simple iteration can be used to solve search problems.

Program 2: Linear Search Using Recursion

Recursion can also be used to implement Linear Search. This approach checks one element per function call, moving through the array until it finds the target.

package main

import "fmt"

func linearSearchRec(arr []int, target int, index int) int {

    if index >= len(arr) {
        return -1
    }

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

    return linearSearchRec(arr, target, index+1)

}

func main() {

    numbers := []int{5, 15, 25, 35, 45}
    target := 25
    index := linearSearchRec(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)
    }

}

In this version, the function calls itself with the next index if the current element does not match the target. It stops either when it finds the element or reaches the end of the array. Recursion helps beginners understand function calls and the flow of execution in a new way.

Program 3: Linear Search for Strings

Linear Search is not limited to numbers. You can also search for strings. This program demonstrates searching for a word in a slice of strings.

package main

import "fmt"

func linearSearchString(arr []string, target string) int {

    for i, value := range arr {

        if value == target {
            return i
        }

    }

    return -1

}

func main() {

    names := []string{"Harry", "Hermione", "Ron", "Luna", "Draco"}
    target := "Luna"
    index := linearSearchString(names, target)

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

}

This program shows that Linear Search works for any data type. By comparing each string in the slice with the target string, it finds the index if present. Beginners can see how the same logic applies beyond numbers.

Program 4: Linear Search with Multiple Occurrences

Sometimes, a target value might appear multiple times. This version finds all indices where the target occurs.

package main

import "fmt"

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

    indices := []int{}

    for i, value := range arr {

        if value == target {
            indices = append(indices, i)
        }

    }

    return indices

}

func main() {

    numbers := []int{5, 10, 5, 20, 5, 30}
    target := 5
    indices := linearSearchAll(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)
    }

}

Here, the program collects all positions where the target is found. This is useful when duplicates are possible, and beginners can understand how to handle multiple results instead of stopping at the first match.

Frequently Asked Questions (FAQ)

Linear Search is simple but sometimes raises questions for beginners.

Q1: What is Linear Search?
Linear Search is a method to find an element in a list by checking each item one by one until the target is found or the list ends.

Q2: When should I use Linear Search?
It’s best for small datasets or when the array is unsorted. For larger sorted datasets, algorithms like Binary Search are more efficient.

Q3: What is the time complexity of Linear Search?
The average and worst-case time complexity is O(n), where n is the number of elements in the array.

Q4: Can Linear Search work with different data types?
Yes. It works with numbers, strings, or any type that can be compared.

Q5: Is Linear Search recursive or iterative?
It can be implemented both ways. Iterative is simpler, while recursive shows how functions can call themselves to achieve the same result.

Conclusion

Linear Search is a fundamental algorithm that every beginner should understand. It’s simple, intuitive, and lays the foundation for learning more advanced search techniques. By practicing both iterative and recursive approaches, as well as searching for numbers, strings, and multiple occurrences, beginners gain a solid understanding of basic search logic.

Start experimenting with your own arrays and targets — try different data types, duplicates, or larger datasets. With practice, Linear Search becomes second nature and sets the stage for mastering more advanced algorithms like Binary Search and Hashing.

Scroll to Top