欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          關(guān)于golang之排序使用

          下面由golang教程欄目給大家介紹golang之排序使用,希望對需要的朋友有所幫助!

          關(guān)于golang之排序使用

          golang標(biāo)準(zhǔn)庫實(shí)現(xiàn)了許多常用的排序方法,比如對整數(shù)序列排序:sort.Ints(),
          那么如果對自定義的數(shù)據(jù)結(jié)構(gòu)排序怎么做呢?
          比如對一個(gè)用戶列表,按他們的積分排序:

          首先定義數(shù)據(jù)結(jié)構(gòu),為了能清楚說明問題,只給兩個(gè)字段。

          type User struct { 	Name  string 	Score int}type Users []User

          golang中想要自定義排序,自己的結(jié)構(gòu)要實(shí)現(xiàn)三個(gè)方法:

          // 摘自: $GOROOT/src/sort/sort.gotype Interface interface { 	// Len is the number of elements in the collection. 	Len() int 	// Less reports whether the element with 	// index i should sort before the element with index j. 	Less(i, j int) bool 	// Swap swaps the elements with indexes i and j. 	Swap(i, j int)}

          這個(gè)設(shè)計(jì)太妙了有沒有,想想我們學(xué)過的排序,都要序列長度,比大小,交換元素。
          那對上述的Users,也就是用戶列表如何使用golang的排序呢?

          先按它說的,實(shí)現(xiàn)這三個(gè)方法:

          func (us Users) Len() int { 	return len(us)}func (us Users) Less(i, j int) bool { 	return us[i].Score < us[j].Score}func (us Users) Swap(i, j int) { 	us[i], us[j] = us[j], us[i]}

          然后就能排序了:

          func main() { 	var us Users	const N = 6  	for i := 0; i < N; i++ { 		us = append(us, User{ 			Name:  "user" + strconv.Itoa(i), 			Score: rand.Intn(N * N), 		}) 	}  	fmt.Printf("%vn", us) 	sort.Sort(us) 	fmt.Printf("%vn", us)}

          可能的輸出為:

          [{user0 5} {user1 15} {user2 11} {user3 11} {user4 13} {user5 6}]
          [{user0 5} {user5 6} {user2 11} {user3 11} {user4 13} {user1 15}]

          可以看到,分?jǐn)?shù)從小到大排列了。

          不過一般我們積分這種東西都是從大到小排序的,只需將
          sort.Sort(us)改成sort.Sort(sort.Reverse(us))就行。

          確實(shí)很方便。

          當(dāng)然,如果出于特殊需要,系統(tǒng)提供的排序不能滿足我們的需要,
          還是可以自己實(shí)現(xiàn)排序的, 比如針對上述,自己來排序(從小到大):

          func myqsort(us []User, lo, hi int) { 	if lo < hi { 		pivot := partition(us, lo, hi) 		myqsort(us, lo, pivot-1) 		myqsort(us, pivot+1, hi) 	}}func partition(us []User, lo, hi int) int { 	tmp := us[lo] 	for lo < hi { 		for lo < hi && us[hi].Score >= tmp.Score { 			hi-- 		} 		us[lo] = us[hi]  		for lo < hi && us[lo].Score <= tmp.Score { 			lo++ 		} 		us[hi] = us[lo] 	} 	us[lo] = tmp	return hi}

          一個(gè)簡單的快速排序,調(diào)用時(shí)只需要myqsort(us)就可以 了。

          總結(jié):

          • 自定義序列要實(shí)現(xiàn)Less, Swap, Len三個(gè)方法 才行

          歡迎補(bǔ)充指正!

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)