欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go?語(yǔ)言sort?中的sortInts?方法

 更新時(shí)間:2022年04月24日 10:36:29   作者:宇宙之一粟  
這篇文章主要介紹了Go?語(yǔ)言sort?中的sortInts?方法,Go?的?sort?包實(shí)現(xiàn)了內(nèi)置和用戶定義類(lèi)型的排序。我們將首先查看內(nèi)置函數(shù)的排序,西瓦嗯更多相關(guān)資料需要的小伙伴可以參考一下

前言:

排序算法一直是很經(jīng)常使用的功能。Go 語(yǔ)言標(biāo)準(zhǔn)庫(kù)為我們提供了方便快捷的 ??sort?? 包 ,這個(gè)包實(shí)現(xiàn)了四種基本排序算法:插入排序、歸并排序、堆排序和快速排序。

一、從有序數(shù)據(jù)中查找值

我們知道,常見(jiàn)查找算法有順序查找和二分查找。而二分查找就是基于有序數(shù)據(jù)的查找方法。而 Go 語(yǔ)言中的 ??sort?? 包就提供了以下幾種查找的方法:

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

二、SearchInts

??SearchInts()?? 函數(shù)是 sort 包的內(nèi)置函數(shù),用于在排序的整數(shù)切片中搜索給定元素 ??x??,并返回 ??Search()?? 指定的索引。

它接受兩個(gè)參數(shù)(??a []int, x int??):

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

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

語(yǔ)法結(jié)構(gòu)如下:

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

返回值: ??SearchInts()?? 函數(shù)的返回類(lèi)型是 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)
}

運(yùn)行該代碼:

$ 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)
}

運(yùn)行結(jié)果:

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]

到此這篇關(guān)于Go 語(yǔ)言sort 中的sortInts 方法的文章就介紹到這了,更多相關(guān)sortInts 方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論