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,low,high);
        quickSortAsc42(arr,low,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,low,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;
}

 

posted @ 2022-03-19 19:14  FredGrit  阅读(34)  评论(0编辑  收藏  举报