go 常用排序算法

冒泡排序

func main() {
    var myslice = []int{4, 2, 3, 1, 6, 5}
    sort(myslice)
    fmt.Println(myslice)
}

func sort(s []int) {
    l := len(s)
    for i := 1; i <= l; i++ {
        for j := 0; j < l-i; j++ {
            if s[j] > s[j+1] {
                s[j], s[j+1] = s[j+1], s[j]
                fmt.Println(s)
            }

        }

    }
}
结果:
[2 4 3 1 6 5]
[2 3 4 1 6 5]
[2 3 1 4 6 5]
[2 3 1 4 5 6]
[2 1 3 4 5 6]
[1 2 3 4 5 6]

插入排序

func main() {
    var myslice = []int{4, 2, 3, 1, 6, 5}
    sort(myslice)
}

func sort(s []int) {
    l := len(s)
    for i := 1; i <= l-1; i++ {
        for j:=i;j > 0;j-- {
            if s[j] < s[j-1] {
                s[j],s[j-1] = s[j-1],s[j]
                fmt.Println(s)
            }
        }

    }
}
结果:
[2 4 3 1 6 5]
[2 3 4 1 6 5]
[2 3 1 4 6 5]
[2 1 3 4 6 5]
[1 2 3 4 6 5]
[1 2 3 4 5 6]

选择排序

func main() {
    var myslice = []int{4, 9, 2, 7, 10, 1, 6, 5}
    sort(myslice)

}

func sort(s []int) {
    l := len(s)
    for i := 1; i <= l-1; i++ {
        var min = s[i-1]
        var loc = i - 1
        for j := i; j < l; j++ {
            if s[j] < min {
                min = s[j]
                loc = j
            }
        }
        s[loc], s[i-1] = s[i-1], min
        fmt.Println(s)
    }
}
结果:
[1 9 2 7 10 4 6 5]
[1 2 9 7 10 4 6 5]
[1 2 4 7 10 9 6 5]
[1 2 4 5 10 9 6 7]
[1 2 4 5 6 9 10 7]
[1 2 4 5 6 7 10 9]
[1 2 4 5 6 7 9 10]

归并排序

func main() {
    var myslice = []int{9, 4,31, 2, 7,17, 10, 1, 6, 5,11}
    mergeSort(myslice)
}

func mergeSort(s []int){
    fmt.Println(sort(s,0))
}

func sort(s []int,start int)[]int{
    if len(s) == 1{
        return s
    }
    mid := len(s)/2
    left := s[:mid]
    fmt.Println(left)
    right := s[mid:]
    fmt.Println(right)
    return merge(sort(left,start),sort(right,mid))
}

func merge(left,right []int)[]int{
    var s = make([]int,0)
    leftLen := len(left)
    rightLen := len(right)
    var rLoc,lLoc int = 0,0
    for  rLoc < rightLen || lLoc < leftLen{
        if lLoc >= leftLen {
            s =append(s,right[rLoc:]...)
            break
        }
        if rLoc >= rightLen {
            s =append(s,left[lLoc:]...)
            break
        }
         if left[lLoc] < right[rLoc]{
            s = append(s,left[lLoc])
            lLoc++
        }else {
                s = append(s,right[rLoc])
                rLoc++
         }
    }
    return s
}
结果:
[9 4 31 2 7]
[17 10 1 6 5 11] 
[9 4]
[31 2 7]
[9]
[4]
[31]
[2 7]
[2]
[7]
[17 10 1]
[6 5 11]
[17]
[10 1]
[10]
[1]
[6]
[5 11]
[5]
[11]
[1 2 4 5 6 7 9 10 11 17 31]  //最终结果

你可能感兴趣的:(go 常用排序算法)