二分partition算法应用

一个二分partition算法,将整个数组分解为小于某个数和大于某个数的两个部分,然后递归进行排序算法。

法一:

int partition(vector<int>&arr, int begin, int end){
    int pivot = arr[begin];
    // Last position where puts the no_larger element.
    int pos = begin;
    for(int i=begin+1; i!=end; i++){
        if(arr[i] <= pivot){
            pos++;
            if(i!=pos){
                swap(arr[pos], arr[i]);
            }
        }
    }
    swap(arr[begin], arr[pos]);
    return pos;
}

 

 

法二:

int partition(vector<int> &nums, int begin, int end)
{
    int pivot = nums[begin];
    while(begin < end)
    {
        while(begin < end && nums[--end] >= pivot);
        nums[begin] = nums[end];
        while(begin < end && nums[++begin] <= pivot);
        nums[end] = nums[begin];
    }
    nums[begin] = pivot;
    return begin;
}

经典的快速排序算法,直接上代码:

void quickSort(vector<int> &nums, int begin, int end)
{
    if(end - begin <= 1)
        return;
    int mid = partition(nums, begin, end);

    quickSort(nums, begin, mid);
    quickSort(nums, mid, end);
}

数组第K大数值查询

class Solution
{
    public:
        int findKthLargest(vector<int> &nums, int k)
        {
            int len = nums.size();
            int res = 0;
            int left = 0;
            int right = len;
            while(left < right)
            {
                int pos = partition(nums, left, right);
                if(pos == len-k)
                {
                    res = nums[pos];
                    break;
                }
                else if(pos < len-k)
                    left = pos+1;
                else
                    right = pos;
            }
            return res;
        }
        int partition(vector<int> &nums, int begin, int end)
        {
            int pivot = nums[begin];
            while(begin < end)
            {
                while(begin < end && nums[--end] >= pivot);
                nums[begin] = nums[end];
                while(begin < end && nums[++begin] <= pivot);
                nums[end] = nums[begin];
            }
            nums[begin] = pivot;
            return begin;
        }
};

 

posted @ 2018-03-06 13:22  左岸繁华右岸殇  阅读(345)  评论(0编辑  收藏  举报