通過leetcode學習常見排序演算法及其Go實現

酒肉穿腸過發表於2019-02-16

問題描述

75. Sort Colors
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

氣泡排序

演算法描述

1 遍歷待排序序列
2 比較相鄰兩個數,不相等則交換位置把大數放在小數後面
3 重複以上步驟,直到待排序序列為空,或無交換髮生,說明排序完成

程式碼實現

/**
 * 最差時間複雜度 O(n^2)
 * 最優時間複雜度 O(n)
 * 平均時間複雜度 O(n^2)
 * 所需輔助空間  O(1)
 * 穩定性 穩定
 **/
func sortColors(nums []int) {
    length := len(nums)
    if length <= 1 {
        return
    }
    swapFlag := false
    temp := 0
    for i := 0; i < length; i++ {
        swapFlag = false
        for j := 0; j < length-i-1; j++ {
            if nums[j] > nums[j+1] {
                temp = nums[j]
                nums[j] = nums[j+1]
                nums[j+1] = temp
                swapFlag = true
            }
        }
        if !swapFlag { // 說明已經排好序
            break
        }
    }
}

選擇排序

演算法描述

1 初始時在序列中找到最小元素,放到序列的起始位置作為已排序序列
2 再從剩餘未排序元素中繼續尋找最小元素,放到已排序序列的末尾
3 重複以上步驟,直到所有元素均排序完畢

程式碼實現

/**
 * 最差時間複雜度 O(n^2)
 * 最優時間複雜度 O(n^2)
 * 平均時間複雜度 O(n^2)
 * 所需輔助空間  O(1)
 * 穩定性 不穩定
 **/
func sortColors(nums []int)  {
    if len(nums) <= 0 {
        return
    }
    
    temp, index := 0, 0
    for i := 0; i < len(nums); i++ { // 已排序列
        index = i
        for j := i + 1; j < len(nums); j++ { // 未排序列
            if nums[j] < nums[index] {
                index = j
                temp = nums[i]
            }
        }
        if index != i {
            nums[i] = nums[index]
            nums[index] = temp
        }
    } 
}

插入排序

演算法描述

1 從第一個元素開始,該元素可以認為已排好序
2 取出下一個元素,在已排序列中從後向前遍歷
3 若已排序列大於新元素,將已排元素移到下一位置
4 重複步驟3,直到找到已排元素小於或者等於新元素的位置
5 將新元素插入到該位置後,重複步驟2~5

程式碼實現

/**
 * 最差時間複雜度 O(n^2)
 * 最優時間複雜度 O(n)
 * 平均時間複雜度 O(n^2)
 * 所需輔助空間  O(1)
 * 穩定性 穩定
 **/
func sortColors(nums []int)  {
    if len(nums) <= 0 {
        return
    }
    
    temp := 0
    for i := 1; i < len(nums); i++ {
        temp = nums[i]
        j := i - 1
        for ; j >= 0 && nums[j] > temp; {
            nums[j+1] = nums[j]
            j--
        }
        nums[j+1] = temp
    } 
}

相關文章