(1) 快速排序算法的程序
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swap1(int arr[], int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void median3(int A[], int left, int right)
{
int center = (left + right) / 2;
if (A[left] > A[center])
swap(&(A[left]), &(A[center]));
if (A[left] > A[right])
swap(&(A[left]), &(A[right]));
if (A[center] > A[right])
swap(&(A[center]), &(A[right]));
swap(&(A[center]), &(A[right - 1]));
}
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
median3(arr, low, high);
int pivot = high - 1;
int i = low;
int j = high - 1;
while (1)
{
while (arr[++i] < arr[pivot]) {}
while (j > low && arr[--j] > arr[pivot]) {}
if (i < j)
{
swap1(arr, i, j);
}
else
{
break;
}
}
if (i < high)
{
swap1(arr, i, high - 1);
}
quickSort(arr, low, i - 1);
quickSort(arr, i + 1, high);
}
}
int arr[500000];
int main()
{
clock_t start, end;
srand(10086);
for (int j = 0; j < 500000; j++)
arr[j] = j;
int n = 500000;
start = clock();
quickSort(arr, 0, n - 1);
end = clock();
printf("time=%f\n", (double)(end - start) / CLOCKS_PER_SEC);
return 0;
}
浙公网安备 33010602011771号