Golang Linear Search Algorithm

1. Introduction

Linear Search, also known as a sequential search, is a simple method used to find a particular value in a list. It checks each element of the list sequentially until a match is found or the whole list has been searched. It's straightforward to implement but is not the most efficient search algorithm, especially when dealing with large lists.

2. Implementation Steps

1. Start from the leftmost element of the list and compare the element being searched for with each element of the list.

2. If the element being searched for is found, return its index.

3. If the element is not found in the list, return -1.

3. Implementation in Golang

package main
import (
	"fmt"
)
// linearSearch function returns the index of the element if found, else returns -1
func linearSearch(arr []int, x int) int {
	for i, item := range arr {
		if item == x {
			return i
		}
	}
	return -1
}
func main() {
	data := []int{20, 40, 80, 60, 10}
	searchNum := 60
	index := linearSearch(data, searchNum)
	if index != -1 {
		fmt.Printf("Element %d is present at index %d.\n", searchNum, index)
	} else {
		fmt.Printf("Element %d is not present in the array.\n", searchNum)
	}
}

Output:

Element 60 is present at index 3.

Explanation:

1. The linearSearch function takes an array and an element as its parameters. It iterates over each element of the array using the range keyword.

2. During each iteration, it checks if the current element matches the element being searched for. If a match is found, it returns the index of the element.

3. If no match is found after scanning the entire list, the function returns -1.

4. The main function initializes an array and the element we want to search for. It then calls the linearSearch function and prints the result based on the return value.

5. While Linear Search is simple and requires no preconditions on the input list (like being sorted), its inefficiency (O(n) time complexity) makes it less preferred for large datasets.

This provides a detailed understanding of the Linear Search algorithm in Golang.


Comments