模仿 Go Sort 排序介面實現的自定義排序

2021-09-16 20:55:20 字數 1568 閱讀 9568

go 語言對於型別的要求非常嚴格,導致我們無法宣告乙個inte***ce型別的切片對其排序。所以這裡模仿 go 的 sort 排序擴充套件包,實現對某個特定型別排序的方法。

若要實現乙個自定義的排序,就要實現 sort 包的排序介面。要排序的集合必須包含乙個數字型別的索引,所以待排序的資料型別只能是陣列或者切片。

// a type, typically a collection, that satisfies sort.inte***ce can be

// sorted by the routines in this package. the methods require that the

// elements of the collection be enumerated by an integer index.

type inte***ce inte***ce

我們將對所有的學生進行排序,學生包含他的姓名以及成績,排序的規則是按照學習的成績排序。

type student struct 

type students student

func (s students) len() int 

// 在比較的方法中,定義排序的規則

func (s students) less(i, j int) bool else if s[i].score > s[j].score else

}func (s students) swap(i, j int)

go 提供了基於快排實現的排序方法,這裡為了體驗為什麼 go 這麼定義 inte***ce 介面,我使用了選擇排序的方法代替 go 的快排。

func sort(s sort.inte***ce) 

}s.swap(minindex, i)

}}

在這個排序中,我使用了介面中定義的三個方法:len(),less(),swap()。最重要的還是less(),沒有它程式就不知道如何去比較兩個未知元素的大小。

為了更好的輸出學生的資訊,重寫學生的字串輸出格式

func (s student) string() string
通過以下程式測試我們的排序演算法

func main() 

selectionsort(arr, len(arr))

fmt.println(arr)

students := student.students{}

sort(students)

for _, student := range students

}

以下是輸出結果:

[1 2 3 4 5 6 7 8 9 10]

student: d 90

student: a 95

student: b 95

student: c 100

Fragment實現Tab 模仿微信介面

推薦關聯文章 推薦關聯文章 步驟 1 新建4個繼承fragment的類和4個布局,分別將布局新增到新建的類中 2 初始化 設定監聽 開啟事務 3 按鍵監聽中顯示對應的fragment 如下 1 設定好4個fragment碎片 4個相似,只貼出乙個碎片步驟 package com.example.le...

模仿微信6 0的介面效果

實現目標 首先自定義屬性 hello world settings 查詢 新增 發起群聊 新增朋友 掃一掃意見反饋 通訊錄發現 我 android id id action search android icon drawable ic launcher android actionviewclas...

golang排序實現 sort介面實現

今天看見群裡再討論排序的sort.inte ce的實現,有童鞋一直搞不定,我就上手了一下,哦耶搞定了,放在這裡.其實很簡單sort.inte ce藉口有三個方法,給自己的struct實現這三個方法,然後用將自己的結構體傳給sort.sort方法就排序完成.當然sort包也有幾個常用的方法sort.f...