Golang Linear Search Algorithm

The linear search method finds a given value within a collection by sequentially checking every element in the collection. The time complexity of the linear search algorithm is O(n). The binary search algorithm and hash tables perform better than this search algorithm.

Golang Linear Search Algorithm

Let's create a file named "linear_search.go" and add the following source code to it:


package main

// importing fmt package
import (
	"fmt"
)

// Linear Search method
func LinearSearch(elements []int, findElement int) bool {
	var element int
	for _, element = range elements {
		if element == findElement {
			return true
		}
	}
	return false
}

// main method
func main() {
	var elements []int
	elements = []int{15, 48, 26, 18, 41, 86, 29, 51, 20}
	fmt.Println(LinearSearch(elements, 48))
}


Run the following command to execute the linear_search.go file:

G:\GoLang\examples>go run linear_search.go
true

Comments