sort.h
#define SWAP(x,y) {int tmp = x; x = y; y = tmp;}
#define N 50000000
#define M 10000000
int Potrition(int* a,int low,int high)//版本一
{
int pivot = a[low];
while (low<high)
{
while (low < high && a[high] >= pivot)
--high;
a[low] = a[high];
while (low < high && a[low] <= pivot)
++low;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
int divide(int* a, int left, int right)//算法导论版本,当然肯定不正宗
{
int i, j;
for (i = left, j = left; i < right; ++i)
{
if (a[i] < a[right])
{
SWAP(a[i], a[j]);
++j;
}
}
SWAP(a[j], a[right]);
return j;
}
void quickSortA(int* a, int left, int right)
{
if (right > left)
{
int pivot = divide(a, left, right);
quickSortA(a, left, pivot - 1);
quickSortA(a, pivot + 1, right);
}
}
void quickSortB(int* a, int low, int high)
{
if (high > low)
{
int pivot = Potrition(a, low, high);
quickSortB(a, low, pivot - 1);
quickSortB(a, pivot + 1, high);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "sort.h"
int main()
{
int* a = (int*)malloc(N * sizeof(int));
int* b = (int*)malloc(N * sizeof(int));
srand(time(NULL));
for (int i = 0; i < N; ++i)
{
a[i] = rand()% M;
}
for (int i = 0; i < N; ++i)
{
b[i] = a[i];
}
//print(a);
time_t beg = time(NULL);
quickSortA(a,0,N-1);
time_t end = time(NULL);
printf("算法导论版本 total time = %lld s\n", end - beg);
beg = time(NULL);
quickSortB(b,0,N-1);
end = time(NULL);
printf("严版本 total time = %lld s\n", end - beg);
return 0;
}
结果是在linux系统上好像两个没有很大的差别,而windows上可能差别会比较大,原因还未知。