Go Program to Implement a Linear Search Algorithm

Searching is one of the most fundamental operations in computer science. Among the various search algorithms, the linear search is the simplest and most straightforward. It sequentially checks each element of the list until a match is found or the whole list has been searched. In this blog post, we'll explore how to implement the linear search algorithm in the Go programming language. 

Program Overview 

In our linear search program: 

Input: A list of elements and a target element to search for. 

Processing: Sequentially traverse the list and compare each element with the target. 

Output: Return the index of the target element if found; otherwise, indicate that the element is not in the list.

Code Program

package main

import "fmt"

// LinearSearch function searches for the target in the provided array.
func LinearSearch(arr []int, target int) int {
    for index, value := range arr {
        if value == target {
            return index  // Return the index if the target is found.
        }
    }
    return -1  // Return -1 if the target is not found.
}

// Main function to execute the program.
func main() {
    array := []int{10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
    target := 110

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

Output:

Element 110 is present at index 6. 

Explanation

Function Declaration: We have a function named LinearSearch that accepts an integer array and a target integer as its parameters. 

Traversal and Comparison: We traverse the provided array using a for loop. For each element, we check if it matches the target. If a match is found, we return the index of the matching element. Not 

Found Scenario: If we traverse the entire array and don't find the target, we return -1 to indicate the target is not present in the array. 

Main Function: This is where our program starts execution. We define an array and a target element. The LinearSearch function is then invoked, and based on its return value, we either print the index of the found element or indicate that it's not present. 

In summary, the linear search algorithm is a fundamental search technique that's easy to understand and implement. While it may not be the most efficient for large datasets, it serves as a stepping stone to understanding more complex search algorithms. And with Go's simplicity and clarity, implementing such algorithms becomes a breeze.

Comments