在本教程中,我們將看到寫一個go語言程序來對一個數組進行降序排序。在數學中,降序是指後面的元素比前面的元素小的順序。
使用外部函數對一個數組進行降序排序
在這個例子中,我們將看到編寫一個程序,使用用戶定義的函數對一個整數陣列進行降序排序。
算法
第1步 – 導入fmt軟件包
第2步 – 定義一個函數sortDesc()來對給定數組進行排序。該函數接受一個參數,即我們希望進行排序的整數數組。
第3步 – 該函數使用兩個for循環和if條件對數組進行排序。
第4步 – 使用第一個for循環遍歷未排序的數組,第二個for循環獲得數組中存在的最小值。
第5步 – 然後用一個臨時變量把較小的數值放在較大的數值之後。
第6步 – 啓動main()函數。
第7步 – 初始化一個整數數組並向其存儲數值。在屏幕上打印未排序的數組。
第8步 – 然後我們需要調用sortDesc()函數,把要排序的數組作爲參數傳給該函數。
第9步 – 存儲函數返回的數組並使用fmt.Println()函數將其打印在屏幕上。
示例
下面的代碼說明了我們如何用go編程語言對一個數組的元素進行降序排序。
package main
import "fmt"
func sortDesc(arr [5]int) [5]int {
for i := 0; i < len(arr); i++ {
for j := 1 + i; j < len(arr); j++ {
if arr[i] < arr[j] {
intermediate := arr[i]
arr[i] = arr[j]
arr[j] = intermediate
}
}
}
return arr
}
func main() {
arr := [5]int{50, 30, 20, 10, 40}
fmt.Println("The unsorted array entered is:", arr)
array := sortDesc(arr)
fmt.Println()
fmt.Println("The final array obtained after sorting is:", array)
}
輸出
The unsorted array entered is: [50 30 20 10 40]
The final array obtained after sorting is: [50 40 30 20 10]
使用Intslice()函數對一個數組進行降序排序
下面的代碼說明了在go編程語言中使用預定義的函數對一個整數數組進行降序排序。
語法
sort.Sort(sort.Reverse(sort.IntSlice(arr)))
IntSlice()函數存在於排序包中,用於對一個整數數組進行排序。該函數接收一個未排序的整數數組,並通過排序返回數組。 Reverse()函數存在於排序包中。該函數接收要以反向順序排序的數據作爲參數,並通過反轉其值返回數組的片斷。
算法
第1步 – 導入fmt和sort包。
第2步 – 啓動main()函數。
第3步 – 初始化一個整數數組並向其存儲數值。在屏幕上打印未排序的數組。
第4步 – 現在我們需要調用sort包中的Ints()函數,將需要排序的數組作爲參數傳給該函數。
第5步 – arr數組現在已經排序了。我們可以用fmt.Println()函數將其打印在屏幕上。
示例
package main
import (
"fmt"
"sort"
)
func main() {
var arr = []int{9, 8, 7, 4, 5, 3}
fmt.Println("Unsorted array of strings is", arr)
sort.Sort(sort.Reverse(sort.IntSlice(arr)))
fmt.Println("The above array is sorted and the result is:", arr)
}
輸出
Unsorted array of strings is [9 8 7 4 5 3]
The above array is sorted and the result is: [9 8 7 5 4 3]
使用Stringslice()方法對一個字符串數組進行降序排序
現在讓我們寫一個程序,使用go編程語言中的預定義函數對一個字符串數組進行降序排序。
語法
sort.Sort(sort.Reverse(sort.StringSlice(arr)))
StringSlice()函數存在於sort包中,它接收要排序的字符串數組作爲參數,並返回排序後的字符串。Reverse()函數存在於sort包中。該函數將待排序的數據作爲一個參數,並通過反轉其值返回數組的片斷。
算法
第1步 – 導入fmt和sort包。
第2步 – 啓動main()函數。
第3步 – 初始化一個字符串數組,並向其存儲數值。在屏幕上打印未排序的數組。
第4步 – 現在我們需要調用排序包中的StringSlice()函數,將需要排序的數組作爲參數傳給該函數。
第5步 – arr數組現在已經排序了。我們可以用fmt.Println()函數將其打印在屏幕上。
示例
package main
import (
"fmt"
"sort"
)
func main() {
var arr = []string{"a", "b", "c", "d", "s"}
fmt.Println("Unsorted array of strings is", arr)
sort.Sort(sort.Reverse(sort.StringSlice(arr)))
fmt.Println("The above array is sorted and the result is:", arr)
}
輸出
Unsorted array of strings is [a b c d s]
The above array is sorted and the result is: [s d c b a]
結論
我們已經成功地編譯並執行了一個Go語言程序,將一個數組按降序排序,並附有實例。