码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-07-03 13:07:47      阅读:536      评论:0      收藏:0      [点我收藏+]

标签:

 

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 整数排序之二

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5637862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!