go语言种的常用排序方法

go语言种的常用排序方法

Go语言中常用的排序方法有以下几种:

  1. 冒泡排序(Bubble Sort)
go 复制代码
func BubbleSort(arr []int) []int {
    n := len(arr)
    for i := 0; i < n-1; i++ {
        for j := 0; j < n-i-1; j++ {
            if arr[j] > arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]
            }
        }
    }
    return arr
}
  1. 插入排序(Insertion Sort)
go 复制代码
func InsertionSort(arr []int) []int {
    n := len(arr)
    for i := 1; i < n; i++ {
        key := arr[i]
        j := i - 1
        for j >= 0 && arr[j] > key {
            arr[j+1] = arr[j]
            j--
        }
        arr[j+1] = key
    }
    return arr
}
  1. 选择排序(Selection Sort)
go 复制代码
func SelectionSort(arr []int) []int {
    n := len(arr)
    for i := 0; i < n-1; i++ {
        minIndex := i
        for j := i + 1; j < n; j++ {
            if arr[j] < arr[minIndex] {
                minIndex = j
            }
        }
        arr[i], arr[minIndex] = arr[minIndex], arr[i]
    }
    return arr
}
  1. 快速排序(Quick Sort)
go 复制代码
func QuickSort(arr []int) []int {
    if len(arr) <= 1 {
        return arr
    }
    pivot := arr[0]
    var less, greater []int
    for _, num := range arr[1:] {
        if num <= pivot {
            less = append(less, num)
        } else {
            greater = append(greater, num)
        }
    }
    var sorted []int
    sorted = append(sorted, QuickSort(less)...)
    sorted = append(sorted, pivot)
    sorted = append(sorted, QuickSort(greater)...)
    return sorted
}

以上是一些常用的排序方法,你可以根据需要选择适合的方法来对切片进行排序。

相关推荐
不会就选b4 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
千里码aicood8 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
做cv的小昊8 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له9 小时前
World-In-World: World Models in a Closed-Loop World
算法
念何架构之路10 小时前
go-grpc使用
rpc·golang
Discipline102911 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder11 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!11 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
weixin_3077791311 小时前
基于睿擎工业开发平台的预训练视觉模型轻量化适配与低代码部署优化
开发语言·算法