go实现常见排序算法

2022-09-07 11:24:15 浏览数 (1)

代码语言:javascript复制
冒泡:
package main
 
import (
    "fmt"
)
 
func BubbleSort(arr []int) []int {
    // 改进的冒泡排序
    num := len(arr) //:=自动匹配变量类型
    for i := 0; i < num; i   {
        status := false
        for j := i   1; j < num; j   {
            if arr[i] > arr[j] {
                status = true
                arr[i], arr[j] = arr[j], arr[i]
            }
        }
        if status == false {
            break
        }
    }
    return arr
}
 
func main() {
    arr := []int{100, 200, 55, 9, 88, 77, 66, 55, 44, 1, 2, 3, 65, 4, 7, 89, 6, 3, 32, 1, 4, 0, 5, 8, 7}
    fmt.Printf("排序前:%vn", arr)
    NewArr := BubbleSort(arr)
    fmt.Printf("排序后:%v", NewArr)
}
 插入:
package main
 
import "fmt"
 
func main() {
    //插入排序
    arr := []int{1,2,5,8,7,9,6,4,3,0}
    fmt.Println(InertSort(arr))
}
 
 
func InertSort(arr []int)[]int{
    num := len(arr)
    for i:=1; i<num; i  {
        min := arr[i]
        j := i-1
        for j >=0 && arr[j] >= min{
            arr[j 1] = arr[j]
            j--
            arr[j 1] = min
        }
    }
 
    return arr
}
 选择排序:
package main
 
import (
    "fmt"
)
 
func main() {
    arr := []int{1, 2, 5, 8, 7, 4, 3, 6, 9, 0}
    fmt.Println(SelectSort(arr))
}
 
func SelectSort(arr []int) []int {
    num := len(arr)
    for i := 0; i < num; i   {
        min := i
        for j := i   1; j < num; j   {
            if arr[j] < arr[min] {
                min = j
            }
        }
        arr[i], arr[min] = arr[min], arr[i]
    }
    return arr
}
 二分查找:
package main
 
import (
    "fmt"
)
 
func main() {
    arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20}
    fmt.Println(BinarySearch(arr, 5))
}
 
func BinarySearch(arr []int, key int) int {
    low := 0
    high := len(arr)-1
    for arr[low] <= arr[high] {
        if key > low {
            low = key
        } else if key < high {
            high = key
        } else {
            return key
        }
    }
    return -1
 
}

0 人点赞