C库函数qsort()与快速排序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define swap(x, y, t) ((t) = (x), (x) = (y), (y) = (t))

void quicksort(int array[], int left, int right)
{
	int pivot, i, j;
	int temp_value;
	if (left < right)
	{
		i = left;
		j = right + 1;
		pivot = array[left];
		do
		{
			do
			{
				i++;
			}while(array[i] < pivot);
			do
			{
				j--;
			}while(array[j] > pivot);
			if (i < j)
			{
				swap(array[i], array[j], temp_value);
			}
		}while(i < j);
		swap(array[left], array[j], temp_value);
		quicksort(array, left, j-1);
		quicksort(array, j+1, right);
	}
}

int compare(const void* p1, const void* p2)
{
	int i = *(int*)p1;
	int j = *(int*)p2;
	return i-j;
}

int main(void)
{
	srand(time(NULL));
	const int max = 100000;
	int test_array[max] = {0};
	for (int i = 0; i < max; i++)
	{
		test_array[i] = rand();
	}
	clock_t time = clock();
	qsort(test_array, max, sizeof(test_array[0]), compare);
	printf("%d\n", clock()-time);

	for (int j = 0; j < max; j++)
	{
		test_array[j] = rand();
	}
	time = clock();
	quicksort(test_array, 0, max);
	printf("%d", clock()-time);
	return 0;
}

你可能感兴趣的:(C库函数qsort()与快速排序)