Go 语言入门很简单:sort 中的sortInts 方法

举报
宇宙之一粟 发表于 2022/04/24 11:58:46 2022/04/24
【摘要】 从有序数据中查找值我们知道,常见查找算法有顺序查找和二分查找。而二分查找就是基于有序数据的查找方法。而 Go 语言中的 sort 包就提供了以下几种查找的方法:SearchInts(slice ,val)SearchFloats(slice, val)SearchStrings(slice, val)Searh(count, testFunc) SearchIntsSearchInts()...

从有序数据中查找值

我们知道,常见查找算法有顺序查找和二分查找。而二分查找就是基于有序数据的查找方法。而 Go 语言中的 sort 包就提供了以下几种查找的方法:

  • SearchInts(slice ,val)
  • SearchFloats(slice, val)
  • SearchStrings(slice, val)
  • Searh(count, testFunc)

SearchInts

SearchInts() 函数是 sort 包的内置函数,用于在排序的整数切片中搜索给定元素 x,并返回 Search() 指定的索引。

它接受两个参数(a []int, x int):

  • a 是 int 类型的排序切片,
  • x 是要搜索的 int 类型元素,并返回 Search() 指定的索引

注意:如果 x 不存在,可能是 len(a)SearchInts() 结果是插入元素 x 的索引。切片必须按升序排序。

语法结构如下:

func SearchInts(a []int, x int) int

返回值: SearchInts() 函数的返回类型是 int,它返回 Search 指定的索引。

现在来看一个例子:

例子一:

package main

import (
	"fmt"
	"sort"
)

func main() {

	ints := []int{2025, 2019, 2012, 2002, 2022}

	sortInts := make([]int, len(ints))

	copy(sortInts, ints)

	sort.Ints(sortInts)

	fmt.Println("Ints: ", ints)
	fmt.Println("Ints Sorted: ", sortInts)

	indexOf2022 := sort.SearchInts(sortInts, 2022)
	fmt.Println("Index of 2022: ", indexOf2022)
}

运行该代码:

$ go run main.go         
Ints:  [2025 2019 2012 2002 2022]
Ints Sorted:  [2002 2012 2019 2022 2025]
Index of 2022:  3

例子二:

package main

import (
	"fmt"
	"sort"
)

func main() {
	a := []int{10, 20, 25, 27, 30}

	x := 25
	i := sort.SearchInts(a, x)
	fmt.Printf("Element %d found at index %d in %v\n", x, i, a)

	x = 5
	i = sort.SearchInts(a, x)
	fmt.Printf("Element %d not found, it can inserted at index %d in %v\n", x, i, a)

	x = 40
	i = sort.SearchInts(a, x)
	fmt.Printf("Element %d not found, it can inserted at index %d in %v\n", x, i, a)
}

运行结果:

Element 25 found at index 2 in [10 20 25 27 30]
Element 5 not found, it can inserted at index 0 in [10 20 25 27 30]
Element 40 not found, it can inserted at index 5 in [10 20 25 27 30]
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。