linear Search Algorithm

The linear search algorithm is a simple and intuitive method for searching an element in a given list or array. This technique involves iterating through each element in the list one by one and comparing it with the target value that needs to be found. If the current element matches the target value, the search is successful, and the index of the element is returned. If the target value is not found after iterating through the entire list, the algorithm returns an indication that the element is not present in the list. The primary advantage of the linear search algorithm is its simplicity and ease of implementation, making it suitable for small datasets or unordered lists where more sophisticated search algorithms may not be required. However, the linear search algorithm may not be the most efficient choice for larger datasets or cases where the list is sorted, as its time complexity is O(n), meaning that the algorithm's performance degrades linearly with the size of the list. In such cases, other search algorithms, such as binary search or hash-based techniques, can provide better performance and efficiency.
package main
import "fmt"

func search(arr []int, key int) int {
  for i := 0; i < len(arr); i++ {
    if arr[i] == key {
      return i
    }
  }
  return -1
}


func main() {

  searchValue := 100
  arr := []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
  fmt.Println(arr)

  found := search(arr, searchValue)

  if found == -1 {
    fmt.Println("Key not found")
  } else {
    fmt.Printf("Key found at position: %d\n", found)
  }

}

LANGUAGE:

DARK MODE: