快速排序?qū)嵸|(zhì)上是對“冒泡排序”的一種改進(jìn),整個排序過程可概括為:通過N趟的排序?qū)⒃镜呐判驍?shù)據(jù)分為若干塊進(jìn)行分塊排序,而在每趟排序過程中,以指定的關(guān)鍵字將待排數(shù)據(jù)分別分為比關(guān)鍵字大的部分和比關(guān)鍵字小的部分,反復(fù)上述過程,將整個待排數(shù)列分散為若干個小數(shù)列而分別進(jìn)行排序操作。假設(shè)我們現(xiàn)對一列數(shù)進(jìn)行快速排序,其C語言代碼實(shí)現(xiàn)如下:
#include <stdio.h>
int partition(int *data,int low,int high)
{ int t = 0;
t = data[low];
while(low < high)
{ while(low < high && data[high] >= t)
high--;
data[low] = data[high];
while(low < high && data[low] <= t)
low++;
data[high] = data[low];
}
data[low] = t;
return low;
}
void sort(int *data,int low,int high) //快排每趟進(jìn)行時的樞軸要重新確定,由此進(jìn) //一步確定每個待排小記錄的low及high的值
{ if(low >= high)
return ;
int pivotloc = 0;
pivotloc = partition(data,low,high);
sort(data,low,pivotloc-1);
sort(data,pivotloc+1,high);
}
void quick_sort(int *data,int n) //該函數(shù)進(jìn)行sort過程的調(diào)用
{ sort(data,0,n-1); }
int main()
{ int i;
int data[]={49,38,32,98,65,74,12,8};
quick_sort(data,sizeof(data)/sizeof(int));
for( i = 0 ; i < sizeof(data)/sizeof(int); i++)
printf("%d ",data[i]);
printf("\n");
return 0;
}