33,317
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int M = 100000;
int Partition(int a[], int p, int r)
{
int i = p;
int j = r + 1;
int x = a[p];
while(true)
{
while(a[++i] < x);
while(a[--j] > x);
if(i >= j)
break;
swap(a[i], a[j]);
}
a[p] = a[j];
a[j] = x;
return j;
}
int Random(int p, int r)
{
int q = p + rand() % (r - p);
return q;
}
int RandomizedPartition(int a[], int p, int r)
{
int i = Random(p, r);
swap(a[i], a[p]);
return Partition(a, p, r);
}
void RandomizedQuickSort(int a[], int p, int r)
{
if(p < r)
{
int q = RandomizedPartition(a, p, r);
RandomizedQuickSort(a, p, q - 1);
RandomizedQuickSort(a, q + 1, r);
}
}
void PrintArray(int a[], int len)
{
for(int i = 0; i < len; ++i)
cout << a[i] << ' ';
cout << endl;
}
int main()
{
srand(unsigned(time(NULL)));
int a[M] = {0};
for(int i = 0; i < M; ++i)
a[i++] = rand() % M;
cout << "The original array is: ";
PrintArray(a, M);
clock_t start = clock();
RandomizedQuickSort(a, 0, M);
cout << "The sorted array is: ";
PrintArray(a, M);
cout << "The time is: " << (clock() - start) / CLK_TCK << endl;
system("pause");
return 0;
}