Leetcode-- Sort Colors

来源:互联网 发布:算法第四版 kindle 编辑:程序博客网 时间:2024/05/29 03:41

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)。

0 0
原创粉丝点击