首页 > 编程语言 > 详细

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

时间:2016-07-03 13:07:10      阅读:262      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!