sort.interface介面
阿新 • • 發佈:2022-03-01
一個內建的排序演算法需要知道三個東西:序列的長度,表示兩個元素比較的結果,一種交換兩個元素的方式;這就是sort.Interface的三個方法: package sort type Interface interface{ Len() int Less(i, j int) bool Swap(i, j int) } 為了對序列進行排序,我們需要定義一個實現了這個三個方法的型別,然後對這個型別的一個例項應用sort.Sort函式。思考對一個字串切片進行排序,這可能是最簡單啊例子了。下面是這個新的型別StringSlice和它的Len,Less和Swap方法 type StringSlice []string func (p StringSlice) Len() int {return len(p)} func (p StringSlice) Less(i, j int) bool {return p[i] < p[j]} func (p StringSlice) Swap(i, j int) {return p[i], p[j] = p[j], p[i]} 現在我們可以通過像下面這樣將一個切片轉換為一個StringSlice型別來進行排序: sort.Sort(StringSlice(names)) 這個轉換得到一個相同長度,容量,和基於names陣列的切片值;並且這個切片值的型別有三個排序需要的方法。 對字串切片的排序是很常用的需要,所以sort包提供了StringSlice型別,也提供了Strings函式能讓上面這些呼叫簡化成sort.Strings(names) sort.Reverse函式將排序順序轉換成逆序 sort.Reverse函式值得進行更進一步的學習,因為它使用了結構體和介面的組合,這是一個重要的思路。sort包定義了一個不公開的struct型別reverse,它嵌入了一個sort.Interface。reverse的Less方法呼叫了內嵌的sort.Interface值的Less方法,但是通過交換索引的方式使得排序結果變成逆序。 package sort type reverse struct { Interface } func (r reverse) Less(i, j int) bool { return r.Interface.Less(j, i) } func Reverse(data Interface) Interface { return reverse(data) } reverse的另外兩個方法Len和Swap隱式地由原有內嵌的sort.Interface提供。因為reverse是一個不公開的型別,所以匯出函式Reverse返回一個包含原有sort.Interface值的reverse型別例項。 儘管對長度為n的序列排序需要O(n log n)次比較操作,檢查一個序列是否已經有序至少需要n-1次比較。sort包中的lsSorted函式幫我們做這樣的檢查。像sort.Sort一樣,它也使用sort.Interface對這個序列和它的排序函式進行抽象,但是它不會呼叫Swap方法,這段程式碼示範了IntsAreSorted和Ints函式在IntSlice型別上的使用: values := []int{3, 1, 4, 1} fmt.Println(sort.IntsAreSorted(value)) // "false" sort.Ints(values) fmt.Println(values) // "[1 1 3 4]" fmt.Println(sort.IntsAreSorted(values)) // true sort.Sort(sort.Reverse(sort.IntSlice(values))) fmt.Println(values) // [4 3 1 1] fmt.Println(sort.IntsAreSorted(values)) // false
-------------------------------------------
個性簽名:程式碼過萬,鍵盤敲爛!!!
如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,博主在此感謝!