C++快速排序與歸併排序的實現(LeetCode 912)

m0_49252661發表於2020-10-09

快速排序

//快速排序
class Solution {
public:
    int Partions(vector<int>& nums,int start,int end){
        if(nums.size()==0||start<0||end>=nums.size()){
            return 0;
        }
        int index=start;//隨機數取每段的第一個元素即可
        swap(nums[index],nums[end]);
        int small=start-1;
        for(index=start;index<end;++index){
            if(nums[index]<nums[end]){
                ++small;
                swap(nums[small],nums[index]);
            }
        }
        ++small;
        swap(nums[small],nums[end]);
        return small;
    }

    void QuickSort(vector<int>& nums,int start,int end){
        if(start==end) return;
        int index=Partions(nums,start,end);
        if(index>start)
            QuickSort(nums,start,index-1);
        if(index<end)
            QuickSort(nums,index+1,end);
    }

    vector<int> sortArray(vector<int>& nums) {
        int length=nums.size();
        int start=0;
        int end=length-1;
        QuickSort(nums,start,end);
        return nums;
    }
};

歸併排序

// 歸併排序 
class Solution {
public:
    vector<int> mergeSort(vector<int>& nums, int l, int r) {
        if (l > r) return {};
        if (l == r) return {nums[l]};
        vector<int> res;
        int m = l + (r - l) / 2;
        auto ln = mergeSort(nums, l, m);
        auto rn = mergeSort(nums, m + 1, r);
        int i = 0;
        int j = 0;
        while (i < ln.size() && j < rn.size()) {
            if (ln[i] <= rn[j]) {
                res.push_back(ln[i++]);
            } else {
                res.push_back(rn[j++]);
            }
        }
        while (i < ln.size()) res.push_back(ln[i++]);
        while (j < rn.size()) res.push_back(rn[j++]);
        return res;
    }

    vector<int> sortArray(vector<int>& nums) {
        return mergeSort(nums, 0, nums.size() - 1);
    }
};

相關文章