使用线性搜索查找数组中特定元素的首次出现位置的Go语言程序
在这篇Go语言文章中,我们将使用递归和迭代方法,查找使用线性搜索在数组中特定元素的首次出现位置。
线性搜索是一种简单的搜索算法,它从列表或数组的开头开始,逐个检查每个元素,直到找到目标值或搜索完整个列表。它也称为顺序搜索。
语法
func firstOcc(arr []int, target int) int {…}
firstOcc() 函数用于迭代地使用线性搜索查找数组中特定元素的首次出现位置。它接受一个整数数组和目标元素作为参数。
func firstOcc(arr []int, target int, index int) int {…}
firstOcc() 函数用于递归地使用线性搜索查找数组中特定元素的首次出现位置。它接受一个整数数组、目标元素和数组的当前索引作为参数。
算法
步骤1 − 首先,我们需要导入 fmt 包。
步骤2 − 现在,创建一个 firstOcc() 函数,该函数使用线性搜索查找数组中特定元素的首次出现位置。
步骤3 − 它接受一个数组和一个目标元素作为输入,并返回数组中目标元素首次出现位置的索引。
步骤4 − 如果数组中未找到目标元素,则函数返回 -1。
步骤5 − 它使用简单的线性搜索算法从开头遍历数组,并将每个元素与目标元素进行比较。如果找到,它将返回该元素的索引。
步骤6 − 启动 main() 函数。在 main() 函数内部,创建一个包含一些元素的数组。
步骤7 − 定义目标元素。
步骤8 − 现在,调用 firstOcc() 函数并将数组和目标元素作为参数传递给该函数。
步骤9 − 此外,使用 fmt.Printf() 函数在屏幕上打印包含目标元素首次出现位置索引的结果消息。
示例1
在这个示例中,我们将使用迭代方法定义一个 firstOcc() 函数,该函数用于使用线性搜索查找数组中特定元素的首次出现位置。
package main
import "fmt"
func firstOcc(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
func main() {
arr := []int{4, 8, 3, 2, 7, 4, 5, 9, 10}
target := 9
index := firstOcc(arr, target)
if index == -1 {
fmt.Printf("First Occurrence of element %d not found in array\n", target)
} else {
fmt.Printf("First Occurrence of element %d found at index %d\n", target, index)
}
}
输出
First Occurrence of element 9 found at index 7
示例2
在这个示例中,我们将使用递归方法定义一个 firstOcc() 函数,该函数用于使用线性搜索查找数组中特定元素的首次出现位置。
package main
import "fmt"
func firstOcc(arr []int, target int, index int) int {
if index >= len(arr) {
return -1
}
if arr[index] == target {
return index
}
return firstOcc(arr, target, index+1)
}
func main() {
arr := []int{49, 23, 33, 14, 56, 46, 17, 28, 69, 10}
target := 56
index := firstOcc(arr, target, 0)
if index == -1 {
fmt.Printf("First Occurrence of element %d not found in array\n", target)
} else {
fmt.Printf("First Occurrence of element %d found at index %d\n", target, index)
}
}
输出
First Occurrence of element 56 found at index 4
结论
我们已经成功编译并执行了一个Go语言程序,该程序使用递归和迭代方法,通过两个示例查找使用线性搜索在数组中特定元素的首次出现位置。在第一个示例中,我们使用了迭代方法;在第二个示例中,我们使用了递归方法。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP