反向快速排序
Reverse Quick Sort
我正在尝试按降序对给定数组执行快速排序,但输出的第一个数字始终是某个任意数字,例如 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;
}
quickSort(arr, 0, size0 - 1);和 j < end0 排除你的最后一个值。
在 randomPartition() 里面
a[i] = a[temp1];
替换为
a[i] = temp1;
只是一个嘘声:P
我正在尝试按降序对给定数组执行快速排序,但输出的第一个数字始终是某个任意数字,例如 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;
}
quickSort(arr, 0, size0 - 1);和 j < end0 排除你的最后一个值。
在 randomPartition() 里面
a[i] = a[temp1];
替换为
a[i] = temp1;
只是一个嘘声:P