快速排序的三种划分算法

#include<vector>
#include<iostream>
#include<time.h>
using namespace std;

int partition_1(vector<int> &nums,int le,int ri){   //来回填坑法
    if(le>=ri){
        return le;
    }
    int stable=nums[le];
    int i=le,j=ri;
    while(i<j){
        while(i<j and nums[j]>=stable){
            --j;
        }
        if(i==j){break;}
        nums[i++]=nums[j];  //填i的坑
        while(i<j and nums[i]<stable){
            ++i;
        }
        if(i==j){break;}
        nums[j--]=nums[i];  //填j的坑
    }
    nums[i]=stable;
    return i;
}

int partition_2(vector<int>& nums,int le,int ri){   //算法导论的方法
    int stable=nums[ri];
    int i=le-1,j=le;
    while(j<ri){
        if(nums[j]<=stable){
            swap(nums[j],nums[++i]);
        }
        ++j;
    }
    swap(nums[i+1],nums[ri]);
    return i+1;
}

int partition_3(vector<int>&nums,int le,int ri){//对换法(有点特殊 不好推广)
    if(le>=ri){return le;}
    int stable=nums[le];
    int i=le,j=ri;
    while(i<j){
        while(i<j and nums[j]>=stable){
            --j;
        }
        while(i<j and nums[i]<=stable){
            ++i;
        }
        swap(nums[i],nums[j]);
    }
    swap(nums[i],nums[le]);
    return i;
}
void ssort(vector<int>&nums,int le,int ri){
    if(le>=ri){return;}
    //int mi=partition_1(nums,le,ri);
    //int mi=partition_2(nums,le,ri);
    int mi=partition_3(nums,le,ri);
    ssort(nums,le,mi-1);
    ssort(nums,mi+1,ri);
}
void my_sort(vector<int>&nums){
    ssort(nums,0,nums.size()-1);
}

int main(){
    srand(time(0));
    vector<int> nums(100);
    for(auto& num:nums){
        num=rand()%100;
    }
    // nums={3,2,1};
    my_sort(nums);
    for(int num:nums){cout<<num<<" ";}
    getchar();
}
posted @ 2020-02-08 02:51  NeoZy  阅读(493)  评论(0编辑  收藏  举报