再次學習快速排序——優化
阿新 • • 發佈:2019-01-23
今天,我學習了一些優化快速排序的方法。
附上程式碼:
(優化前的程式碼為被註釋掉的程式碼,優化後的程式碼我也用中文註釋加以說明了)
#include <stdio.h>
void swap(int *a, int *b);
void QuickSort(int *a, int low, int high)
{
//if(low < high)
while(low < high) //優化:"尾遞迴",減少遞迴深度
{
int pivot = Partition(a, low, high);
QuickSort(a, low, pivot-1 );
//QuickSort(a, pivot+1, high);
low = pivot+1; //優化:"尾遞迴",減少遞迴深度
}
}
int Partition(int *a, int low, int high)
{
int mid = low + (high-low)/2; //*****
if(a[low] > a[high])
swap(&a[low], &a[high]);
if(a[mid] > a[high]) //優化:"三數取中",平衡遞迴樹
swap(&a[mid], &a[high]);
if (a[low] < a[mid])
swap(&a[low], &a[mid]); //*****
int pivotkey = a[low];
while(low < high)
{
while(low < high && a[high] >= pivotkey)
high--;
//swap(&a[low], &a[high]);
a[low] = a[high]; //優化:減少不必要的交換
while (low < high && a[low] <= pivotkey)
low++;
//swap(&a[low], &a[high]);
a[high] = a[low]; //優化:減少不必要的交換
}
a[low] = pivotkey;
return low;
}
int main()
{
int i;
int a[10] = {7, 3, 5, 8, 0, 4, 9, 1, 6, 2};
for(i = 0; i <10; i++)
printf("%d ", a[i]);
printf("\n");
QuickSort(a, 0, 9);
for(i = 0; i <10; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}