Leetcode-- Sort Colors

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.
Note:
You are not suppose to use the library's sort function for this problem.

解決思路:此題要求說白了就是將亂序的數組按照升序進行排列,而且在排序的過程中是一個穩定的過程,即要求爲穩定排序算法。

像常見的穩定排序算法有好多,比如插入排序,冒泡排序等等。下面附上插入排序的代碼:

class Solution {
public:
    void sortColors(int A[], int n) {
        int i,j;
        int temp;
        for(i=0;i<n;++i)
        {
            temp = A[i];
            j=i-1;
            while(j>=0 && temp<A[j])
            {
                A[j+1] = A[j];
                --j;
            }
            A[j+1] = temp;
        }
        
    }
};
當然,該排序算法時間複雜度爲O(n*logn)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章