linear search Algorithm

The linear search algorithm, also known as the sequential search algorithm, is a fundamental and straightforward method for searching an element in a list or an array. It works by iterating through each element in the list or array one-by-one, comparing the target value to each element until a match is found or the end of the list is reached. Linear search is considered a basic algorithm because of its simplicity and ease of implementation. It does not require any advanced data structures or pre-processing steps, making it universally applicable to any type of list or array. However, the primary disadvantage of the linear search algorithm is its inefficiency, particularly in large datasets. The algorithm has a worst-case time complexity of O(n), meaning that its execution time increases linearly with the size of the input data. In the worst case, the target element could be the last element in the list or not present at all, requiring a full traversal of the entire list. This can be problematic when dealing with substantial amounts of data or when the search operation needs to be performed frequently. In such cases, more advanced search algorithms, such as binary search, interpolation search, or hashing techniques, are often more suitable alternatives.
package main

import "fmt"

func linearSearch(array []int, query int) int {
	for i, item := range array {
		if item == query {
			return i
		}
	}
	return -1
}

func main() {
	
	fmt.Println("Linear search:")
	array := []int{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
	index := linearSearch(array, 10)
	if index == -1 {
		fmt.Println("Number not found")
	} else {
		fmt.Println("Index: ", index)
		fmt.Println("array[", index, "] = ", array[index])
	}
}

LANGUAGE:

DARK MODE: