基礎演算法之排序演算法

我濤發表於2019-02-15

排序演算法的Golang實現

package main

import (
    "fmt"
)
//氣泡排序:升序
func BubbleSort(s []int)  {
    for i:= 0;i < len(s);i++{
        for j := 0;j < len(s) - 1 - i;j++{
            if s[j] > s[j+1] {
                temp := s[j]
                s[j] = s[j+1]
                s[j+1] = temp
            }
        }
    }
}

//選擇排序:升序
func SelectSort(nums []int)  {
    for i := 0;i < len(nums);i++{
        min := nums[i]
        minIndex := i
        for j := i + 1;j < len(nums);j++{
            if min > nums[j] {
                min = nums[j]
                minIndex = j
            }
        }
        nums[minIndex] = nums[i]
        nums[i] = min
    }
}

//快速排序
func QuickSort(s []int,left,right int)  {
    sort := func(s []int,low,high int)int {
        tmp := s[low]
        for low < high{
            for low < high && s[high] >= tmp{
                high--
            }
            s[low],s[high] = s[high],s[low]
            for low < high && s[low] <= tmp{
                low++
            }
            s[low],s[high] = s[high],s[low]
        }
        return low
    }
    if left < right {
        index := sort(s,left,right)
        QuickSort(s,left,index-1)
        QuickSort(s,index+1,right)
    }
}

//堆排序
func heapSort(s []int)  {
    heapAdjust := func(s []int,parent,len int) {
        var i int
        for 2 * parent + 1 < len{
            lchild := 2 * parent + 1
            rchild := lchild + 1
            i = lchild
            //取出兩個子節點中最大的一個
            if rchild < len && s[rchild] > s[lchild]{
                i = rchild
            }
            //如果最大節點大於父節點則交換,否則退出迴圈
            if s[i] > s[parent] {
                s[parent],s[i] = s[i],s[parent]
                parent = i
            }else {
                break
            }
        }
    }
    //從最後一個非葉子節點開始調整(len(s)/2 - 1)
    for i := len(s)/2 - 1;i >= 0;i--{
        heapAdjust(s,i,len(s))
    }
    for i := len(s) - 1;i > 0;i--{
        s[0],s[i] = s[i],s[0]
        heapAdjust(s,0,i)
    }
}

//歸併排序
func merge(left,right []int) []int  {
    result := make([]int,0)
    m,n := 0,0
    l,r := len(left),len(right)
    for m < l && n < r {
        if left[m] > right[n] {
            result = append(result,right[n])
            n++
            continue
        }
        result = append(result,left[m])
        m++
    }
    result = append(result,right[n:]...)
    result = append(result,left[m:]...)
    return result
}

func mergeSort(arr []int) []int {
    if len(arr) < 2 {
        return arr
    }
    i := len(arr)/2
    left := mergeSort(arr[0:i])
    right := mergeSort(arr[i:])
    result := merge(left,right)
    return result
}

func main() {
    //陣列是屬於值型別,方法傳遞的話應該是副本
    array := []int{9,20,1,3,2,80,76}
    //BubbleSort(array)
    //SelectSort(array)
    //QuickSort(array,0,len(array) - 1)
    //堆排序
    //heapSort(array)
    //歸併排序
    array = mergeSort(array)
    fmt.Println(array)
}

相關文章