C/C++教程

C++ quick sort ascendingly and descendingly

本文主要是介绍C++ quick sort ascendingly and descendingly,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
void Util::getArray23(int *arr, int len)
{
    srand(time(NULL));
    for (int i = 0; i < len; i++)
    {
        arr[i] = rand();
    }
}

void Util::printArray24(int *arr, int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << "\t";
    }
    cout << endl
         << endl;
}

Ascendingly

void Util::quickSortAsc42(int *arr, int low, int high)
{
    if(low<high)
    {
        int pivot=partitionAsc43(arr,0,high);
        quickSortAsc42(arr,0,pivot-1);
        quickSortAsc42(arr,pivot+1,high);
    }
}

int Util::partitionAsc43(int *arr,int low,int high)
{
    int pivot=arr[high];
    int i=low-1;
    for(int j=low;j<=high;j++)
    {
        if(arr[j]<pivot)
        {
            i++;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return i+1;
}

void Util::quickSortAsc44(int len)
{
    int *arr=new int[len];
    getArray23(arr,len);
    cout<<"Before quick sort ascendingly:"<<endl;
    printArray24(arr,len);
    cout<<"After quick sort ascendingly:"<<endl;
    quickSortAsc42(arr,0,len-1);
    printArray24(arr,len);
    cout<<"Finished in void Util::quickSort44(int len) and now is "<<getTimeNow()<<endl;
}
g++ -g -std=c++2a -I. *.cpp ./Model/*.cpp -o h1 -luuid -lpthread

 

 

 

Descendingly

int Util::partitionDesc45(int *arr,int low,int high)
{
    int pivot=arr[high];
    int i=low-1;
    for(int j=low;j<=high;j++)
    {
        if(arr[j]>pivot)
        {
            i++;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return i+1;
}

void Util::quickSortDesc46(int *arr,int low,int high)
{
    if(low<high)
    {
        int pivot=partitionDesc45(arr,0,high);
        quickSortDesc46(arr,0,pivot-1);
        quickSortDesc46(arr,pivot+1,high);
    }
}

void Util::quickSortDesc47(int len)
{
    int *arr=new int[len];
    getArray23(arr,len);
    cout<<"Before quick sort descendingly:"<<endl;
    printArray24(arr,len);
    cout<<"After quick sort descendingly:"<<endl;
    quickSortDesc46(arr,0,len-1);
    printArray24(arr,len);
    cout<<"Finished in void Util::quickSortDesc47(int len) and now is "<<getTimeNow()<<endl;
}

 

这篇关于C++ quick sort ascendingly and descendingly的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!