[LintCode] Sort Integers II 整数排序之二

 

Given an integer array, sort it in ascending order. Use quick sort, merge sort, heap sort or any O(nlogn) algorithm.

Example

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

 

 

 

解法一:

// Quick sort
class Solution {
public:
    /**
     * @param A an integer array
     * @return void
     */
    void sortIntegers2(vector<int>& A) {
        quick_sort(A, 0, A.size() - 1);
    }
    void quick_sort(vector<int> &A, int start, int end) {
        if (start >= end) return;
        int pivot = end;
        int pos = partition(A, start, end, pivot);
        quick_sort(A, start, pos - 1);
        quick_sort(A, pos + 1, end);
    }
    int partition(vector<int> &A, int start, int end, int pivot) {
        int left = start, right = end;
        while (true) {
            while (left < right && A[left] < A[pivot]) ++left;
            while (left < right && A[right] >= A[pivot]) --right;
            if (left == right) break;
            swap(A[left], A[right]);
        }
        swap(A[left], A[end]);
        return left;
    }
};

 

你可能感兴趣的:([LintCode] Sort Integers II 整数排序之二)