Go语言程序:数组排序


在本教程中,我们将学习如何编写一个Go语言程序,使用三种不同的方法对数组进行排序。

使用用户自定义函数对整数数组进行排序

以下代码演示了如何使用用户自定义函数在Go语言中对数组元素进行排序。

算法

步骤 1 − 导入fmt包。

步骤 2 − 定义一个名为sortArray()的函数,该函数将对给定的数组进行排序。

步骤 3 − 将要排序的数组作为参数传递给此函数。此函数使用两个for循环遍历数组。

步骤 4 − 如果数组的当前元素大于前一个元素,则需要交换它们的位置。

步骤 5 − 重复此过程,直到for循环遍历所有数组元素。返回新形成的数组。

步骤 6 − 开始主函数。

步骤 7 − 初始化一个整数数组并在屏幕上打印它。

步骤 8 − 调用sortArray()函数。

步骤 9 − 将函数返回的数组存储在一个名为result的变量中,并使用fmt.Println()函数在屏幕上打印它。

示例

package main
import "fmt"

// defining a sortArray function to sort the given array
func sortArray(arr [5]int) [5]int {
   for i := 0; i <= len(arr)-1; i++ {
      for j := 0; j < len(arr)-1-i; j++ {
         if arr[j] > arr[j+1] {
            arr[j], arr[j+1] = arr[j+1], arr[j]
         }
      }
   }
   return arr
}
func main() {
   arr := [5]int{50, 30, 20, 10, 40}
   fmt.Println("The unsorted array entered is:", arr)
   result := sortArray(arr)
   fmt.Println("The sorted array is:", result)
   fmt.Println()
   arr = [5]int{2, 8, 6, 3, 1}
   fmt.Println("The unsorted array entered is:", arr)
   result = sortArray(arr)
   fmt.Println("The sorted array is:", result)
}

输出

The unsorted array entered is: [50 30 20 10 40]
The sorted array is: [10 20 30 40 50]

The unsorted array entered is: [2 8 6 3 1]
The sorted array is: [1 2 3 6 8]

使用预定义函数按升序排序字符串数组

以下代码演示了如何在Go编程语言中对字符串数组进行排序。

语法

Sort.Strings(strs)

sort包中的Strings()函数接受要排序的字符串数组作为参数,并返回已排序的字符串。

算法

步骤 1 − 导入fmt和sort包。

步骤 2 − 开始main()函数。

步骤 3 − 初始化一个字符串数组并向其中存储值。在屏幕上打印未排序的数组。

步骤 4 − 现在需要调用sort包中的strings函数,并将要排序的数组作为参数传递给该函数。

步骤 5 − strs数组现在已排序。可以使用fmt.Println()函数在屏幕上打印它。

示例

package main
import (
   "fmt"
   "sort"
)
func main() {
   var strs = []string{"c", "a", "b"}
   fmt.Println("Unsorted array of strings is", strs)
   sort.Strings(strs)
   fmt.Println("The above array is sorted and the result is:", strs)
}

输出

Unsorted array of strings is [c a b]
The above array is sorted and the result is: [a b c]

结论

我们已经成功编译并执行了一个Go语言程序来对数组进行排序,并附带了示例。

更新于: 2023年1月2日

5K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.