经典快排与随机快排

#include <iostream>
using namespace std;
//快排分为经典快排,和随机快排
//经典快排以数组左值或者右值为枢纽,进行排序,时间复杂度,按最坏情况算法,为O(N^2)
//而随机快排是以数组中的随机值为枢纽,是有概率的,因此,随机的快排的时间复杂度,是以期望计算,有如下结论:随机快排的时间复杂度为O(N*logN)



//修改后的荷兰国旗问题
int* particion(int array[],int l,int r)
{
    int less=l-1;
    int more=r+1;
    int current=l;
    while (current<more) {
        if (array[current] < array[r]) {
            std::swap(array[++less], array[current++]);
        } else if (array[current] > array[r]) {
            std::swap(array[--more] , array[current]);

        } else {
            current++;
        }
    }

    static int rearray[2];
    rearray[0]=less;
    rearray[1]=more;
    cout<<rearray[0]<<" "<<rearray[1];
    cout<<"----"<<endl;

    return rearray;
}



void myquicksort(int array[], int l,int r)
{
    if (l<r) {
        int *a = particion(array, l, r);
        myquicksort(array, l, a[0]);
        myquicksort(array, a[1], r);
    }
}


int main() {
    std::cout << "测试改进后的荷兰国旗问题(以右值为枢纽值)" << std::endl;
    int myarray[]={1,3,2,4,6,8,9,11,23,45,9};
    int *a1=particion(myarray,0,10);


    for (int i = 0; i <11 ; i++) {
        std::cout<<myarray[i]<<" ";
    }
    std::cout<<std::endl;

    std::cout<<"a1[0]:"<<a1[0]<<std::endl;
    std::cout<<"a1[1]:"<<a1[1]<<std::endl;

    cout<<"测试以荷兰国旗为基础的经典快排"<<endl;

    myquicksort(myarray,0,10);
    for (int i = 0; i <11 ; i++) {
        std::cout<<myarray[i]<<" ";
    }
    std::cout<<std::endl;

    
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章