[LintCode] Sort Integers 整數排序


 

Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.

Example

Given [3, 2, 1, 4, 5], return [1, 2, 3, 4, 5].

 

這道題讓我們實現最基本的幾個O(n2)的排序算法,選擇排序,冒泡排序和插入排序,都是最基本的排序算法。我們一個一個來看,首先來看冒泡排序,算法思路很簡單,遍歷數組,把當前數字的后面所有的數字都遍歷一遍,遇到小的跟當前數字交換,這樣遍歷的過程中,所有大的數字就像氣泡一樣都到數組的后面去了,這也是為啥叫冒泡排序的原因,參見代碼如下:

 

解法一:

// Bubble sort
class Solution {
public:
    /**
     * @param A an integer array
     * @return void
     */
    void sortIntegers(vector<int>& A) {
        for (int i = 0; i < A.size(); ++i) {
            for (int j = i + 1; j < A.size(); ++j) {
                if (A[i] > A[j]) {
                    swap(A[i], A[j]);
                }
            }
        }
    }
};

 

下面來看插入排序,算法思路是遍歷數組,從A[i]開始往前比,如果遇到A[i] < A[i - 1],那么交換兩者並--i,直到i=0位置停止,參見代碼如下:

 

解法二:

// Insertion sort
class Solution {
public:
    /**
     * @param A an integer array
     * @return void
     */
    void sortIntegers(vector<int>& A) {
        for (int i = 1; i < A.size(); ++i) {
            while (i > 0 && A[i] < A[i - 1]) {
                swap(A[i], A[i - 1]);
                --i;
            }
        }
    }
};

 

選擇排序也不難,思路是遍歷數組,對於當前位置i,我們定義一個變量min_idx,用來記錄當前位置往后的最小值的坐標,我們通過遍歷之后所有的數字來找到最小值的坐標,然后交換A[i]和A[min_idx]即可,參見代碼如下:

 

解法三:

// Selection sort
class Solution {
public:
    /**
     * @param A an integer array
     * @return void
     */
    void sortIntegers(vector<int>& A) {
        for (int i = 0; i < A.size(); ++i) {
            int min_idx = i;
            for (int j = i + 1; j < A.size(); ++j) {
                if (A[j] < A[min_idx]) {
                    min_idx = j;
                }
            }
            swap(A[i], A[min_idx]);
        }
    }
};

 

參考資料:

https://luqinblog.wordpress.com/2016/02/29/sort-integers/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM