[编程珠玑读书笔记]最好的快速排序与库函数中的排序函数比较

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
using namespace std;

const int MAX = 100000;
void swap( int *data, int i, int j)
{
	int temp = data[i];
	data[i] = data[j];
	data[j] = temp;
}
void InsertSort3( int *data, int n)
{
	int i, j, temp;
	for( i = 1; i< n; i++)
	{
		temp = data[i];
		for( j = i; data[j - 1] > temp&& j > 0; j--)
			data[j ] = data[j - 1];
		data[j] = temp;	
	}
}

void QuickSort3( int *data, int l ,int u)
{
	int i, j;
	if ( u - l < 50) return;
	swap(data,l, rand() %( u - l ) + l);
	int temp;
	temp = data[l];
	i = l;
	j = u + 1;
	while( true)
	{
		do  i++;  while( i <= u && data[i] < temp);
		do  j--;  while( data[j] > temp);
		if( i > j )
			break;		
		int t = data[i]; data[i] = data[j]; data[j] = t;

	} 
	swap( data, l, j);
	QuickSort3(data, l , j -1);
	QuickSort3(data, j + 1 , u);
}
int main()
{
	srand(5);
	int data[ MAX];
	int dup_data[MAX];

	const int denominator = MAX * 10;
	double BegTime, EndTime;
	for( int i = 0; i < MAX; i++)
	{
		data[i] = rand() % denominator;
	}

	memcpy( dup_data, data, MAX);

	BegTime = clock();
	QuickSort3( data, 0, MAX - 1);
	InsertSort3( data, MAX);
	EndTime = clock();
	printf("time of QucikSort3 && InsertSort test is : %g ms \n", (EndTime - BegTime ) / 1000);


	BegTime = clock();
	sort( dup_data,dup_data +  MAX - 1);
	EndTime = clock();
	printf("time of sort test is : %g ms \n", (EndTime - BegTime ) / 1000);
	
	BegTime = clock();
	QuickSort3( data, 0, MAX - 1);
	InsertSort3( data, MAX);
	EndTime = clock();
	printf("time of QucikSort3 && InsertSort test is : %g ms \n", (EndTime - BegTime ) / 1000);


	BegTime = clock();
	sort( dup_data,dup_data +  MAX - 1);
	EndTime = clock();
	printf("time of sort test is : %g ms \n", (EndTime - BegTime ) / 1000);
return 0;
}

你可能感兴趣的:(编程,读书)