464. 整数排序 II

提示

        LintCode中的相关算法题实现代码,可以在我的GitHub中下载。

题目需求

给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。

样例

给出 [3, 2, 1, 4, 5], 排序后的结果为 [1, 2, 3, 4, 5]

解题思路

    使用快排。

实现代码

class Solution {
public:
    /**
     * @param A: an integer array
     * @return: nothing
     */
    void sortHelper(vector<int> &A,int low,int high)
    {
        if(low>=high) return;
        int first=low;
        int second=high;
        int target=A[first];
        while(first<second)
        {
            while(first<second&&A[second]>=target)
            {
                second--;
            }
            A[first]=A[second];
            while(first<second&&A[first]<=target)
            {
                first++;
            }
            A[second]=A[first];
        }
        A[first]=target;
        sortHelper(A,low,first-1);
        sortHelper(A,first+1,high);
    }
    void sortIntegers2(vector<int> &A) {
        // write your code here
        sortHelper(A,0,A.size()-1);
    }
};

猜你喜欢

转载自blog.csdn.net/oeljeklaus/article/details/80653486