反向快速排序

时间:2016-09-14 14:06:20

标签: c++ c++11 quicksort

我试图按递减顺序对给定数组执行快速排序,但第一个数字输出总是一些任意数字,如456752。

我无法确定问题的根源。请帮忙

#include <iostream>
#include <cstdlib>
using namespace std;

long randPartition(long a[],long start,long end0)
{
    long pivot = start + rand()%(end0 - start);

    //swap a[end] with [pivot]
    long temp = a[end0];
    a[end0] =  a[pivot];
    a[pivot] = temp;

    //now partitioning
    long i = start;
    for(int j = start; j < end0 ; j++)
    {
        if(a[j] > a[end0])
        {
            long temp1 = a[j];
            a[j] = a[i];
            a[i] = a[temp1];
            i++;
        }
    }

    //swapping pivot with its correct position
    long temp2 = a[end0];
    a[end0] = a[i];
    a[i] = temp2;

    return i;
}

void quickSort(long ar[],long start,long end0)
{
    if (start < end0)
    {
        long i = randPartition(ar,start,end0);
        quickSort(ar,start,i-1);
        quickSort(ar,i+1,end0);
    }
}

int main()
{
    int testCases;
    cin >> testCases;

    while(testCases--)
    {
        long size0;
        cin >> size0;
        long arr[size0];

        for(int i = 0; i < size0; i++)
        {
            cin >> arr[i];
        }
        //cin >> endl;

        //using quick sort algo
        quickSort(arr, 0, size0 - 1);

        //printing the sorted array
        for(int j = 0; j < size0; j++)
        {
            cout << arr[j] << " ";
        }
        cout << endl;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

inside randomPartition()在

a[i] = a[temp1];

替换为

a[i] = temp1;

只是一个booboo:P

答案 1 :(得分:-1)

quickSort(arr,0, size0 - 1 );并且j &lt; end0排除您的上一个值。