Go – Linear Search in Golang

Hello everyone, in this tutorial, we will show you how to write a simple Linear Search in Golang. The following example program has been tested and shared in the same post.

Linear Search in Golang

What is Linear Search?

The Linear Search is a searching algorithm, which will search an element from the given items or array. It start from leftmost element of an array and compare the given item with each element of an array, If item matches with an element the algorithm can return the index or item itself from array, else it will return -1 as an output, which means item is not present in the array.

Function – Linear Search in Golang

The below function is responsible to search an item from given array by using linear search algorithm.

// function responsible to perform linear search
func linearSearch(numbers []int, item int) int {

	if numbers != nil && len(numbers) > 0 {

		for i := 0; i< len(numbers); i++ {

			if numbers[i] == item {
				return numbers[i]
			}

		}

	}

	return -1
}


Full Example

package main

import "fmt"

func linearSearch(numbers []int, item int) int {

	if numbers != nil && len(numbers) > 0 {

		for i := 0; i< len(numbers); i++ {

			if numbers[i] == item {
				return numbers[i]
			}

		}

	}

	return -1
}

func main() {

	numbers := []int{5, 3, 4, 2, 1, 6, 7, 8, 10, 9}

	result := linearSearch(numbers, 7)

	if result != -1 {
		fmt.Println("Item",result,"is found!")
	}
}


Output

Item 7 is found!

References