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

Posted Grandyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 整数排序之二的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Divide Two Integers

[LintCode] Wiggle Sort 扭动排序

lintcode-medium-Sort Colors

Sort Integers

lintcode-medium-Sort List

Sort Integers II