久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    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)排序怎么做呢?
      比如對一個用戶列表,按他們的積分排序:

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

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

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

      // 摘自: $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)}

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

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

      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}

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

      總結(jié):

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

      歡迎補(bǔ)充指正!

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