快速排序

快速排序原理:[https://www.jianshu.com/p/497b8ee8b517[(https://www.jianshu.com/p/497b8ee8b517)
go代码实现:

package main

import (
    "fmt"
)

/*
快速排序:每一轮排序将待排序数分为两部分,然后递归
 */

func parse(a []int, begin int, end int) int {
    index := a[begin]
    for begin < end {
        for begin < end && a[end] >= index {
            end--
        }
        a[begin] = a[end]

        for begin < end && a[begin] <= index {
            begin++
        }
        a[end] = a[begin]
    }
    a[begin] = index

    return begin
}

func quick_sort(a []int, begin int, end int) {
    if begin < end {
        flag := parse(a, begin, end)
        quick_sort(a, begin, flag-1)
        quick_sort(a, flag+1, end)
    }
}
func main() {
    a := []int{2,3,5,2,1,4}
    fmt.Println(a)
    quick_sort(a, 0, len(a)-1)
    fmt.Println(a)
}

运行结果:

GOROOT=C:\Go #gosetup
GOPATH=F:\goPath #gosetup
C:\Go\bin\go.exe build -o C:\Users\windows10\AppData\Local\Temp\___go_build_quick_sort_go.exe F:/code/test/quick_sort/quick_sort.go #gosetup
C:\Users\windows10\AppData\Local\Temp\___go_build_quick_sort_go.exe #gosetup
[2 3 5 2 1 4]
[1 2 2 3 4 5]

Process finished with exit code 0

你可能感兴趣的:(快速排序)