首先上一个正常版的,这种版本的程序对于升序或者降序的数组,会达到最差情况。
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int partition(int* A, int p, int r)
{
if (p < r)
{
int x = A[r];
int i=p-1, j;
int temp;
for (j = p; j < r; j++)
{
if (A[j] <= x)
{
i++;
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
temp = A[i + 1];
A[i + 1] = A[r];
A[r] = temp;
return i + 1;
}
}
void quickSort(int* A, int p, int r)
{
if (p < r)
{
int q = partition(A, p, r);
quickSort(A, p, q - 1);
quickSort(A, q + 1, r);
}
}
void main()
{
int n = 100000; //排序元素长度
int* A = new int[n];
for (int i = 0; i <n; i++)
{
A[i] = rand() % 1000;
}
clock_t start, finish;
double totaltime;
start = clock();
quickSort(A,0,n-1);
finish = clock();
totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
/*for (int i = 0; i < n; i++)
{
cout << A[i] << " ";
}
cout << endl;*/
cout << "堆排序的运行时间为" << totaltime << "秒!" << endl;
system("pause");
}
然后上一个随机版本的,随机就是在使用快排之前,先对数组进行随机化处理。
但是这样太2了,所以我的策略是(其实是书上抄的),随机选取r,然后和最后一位交换位置。
#include <iostream>
#include <stdlib.h>
#include<time.h>
using namespace std;
int partition(int* A, int p, int r)
{
if (p < r)
{
int r1 = (rand() % (r - p + 1)) + p;
int temp=A[r1];
A[r1] = A[r];
A[r] = temp;
int x = A[r];
int i=p-1, j;
for (j = p; j < r; j++)
{
if (A[j] <= x)
{
i++;
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
temp = A[i + 1];
A[i + 1] = A[r];
A[r] = temp;
return i + 1;
}
}
void quickSort(int* A, int p, int r)
{
if (p < r)
{
int q = partition(A, p, r);
quickSort(A, p, q - 1);
quickSort(A, q + 1, r);
}
}
void main()
{
int n = 100000; //排序元素长度
int* A = new int[n];
for (int i = 0; i <n; i++)
{
A[i] = rand() % 1000;
}
clock_t start, finish;
double totaltime;
start = clock();
quickSort(A,0,n-1);
finish = clock();
totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
/*for (int i = 0; i < n; i++)
{
cout << A[i] << " ";
}
cout << endl;*/
cout << "堆排序的运行时间为" << totaltime << "秒!" << endl;
system("pause");
}