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.
Comments
Post a Comment
Leave Comment