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

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

問題描述

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    } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.