golang 快速排序

cmsmdn 2020-03-03

golang 快速排序
package main

import (
    "fmt"
    "strconv"
)

func quickSort(arr []int, low, high int) {
    if low < high {
        var pivot = partition(arr, low, high)
        quickSort(arr, low, pivot)
        quickSort(arr, pivot + 1, high)
    }
}
func partition(arr []int,low,high int) int  {
    var pivot = arr[low]
    var i = low
    var j= high
    // 6 5 4 3 2 1
    // 6 1 2 3 4 7
    for i< j{
        for arr[j] >= pivot && j > low {
            j--
        }
        //
        for arr[i]<= pivot && i<high{
            i++
        }
        if i<j {
            arr[i],arr[j]=arr[j],arr[i]
        }
    }
    arr[low],arr[j] = arr[j],pivot
    //
    return j
}

func printArray(arr []int) {
    for i := 0; i < len(arr); i++ {
        fmt.Print(strconv.Itoa(arr[i]) + " ")
    }
    fmt.Println("")
}

func main() {
    var arr = []int { 15, 3, 12, 6, -9, 9, 0,8,8 }
    fmt.Print("Before Sorting: ")
    printArray(arr)
    quickSort(arr, 0, len(arr) - 1)
    fmt.Print("After Sorting: ")
    printArray(arr)
}

参考文件:

最常用的排序-快速排序

Quick Sort Algorithm in Go Programming

相关推荐