快速排序屬於交換類排序,是對冒泡排序的一種改進。基本思想基於分治法:在待排序表中任取一個元素pivot作爲基準,通過一趟排序將排序表劃分爲兩部分,使得大於pivot的元素在一個表中,小於pivot的元素在一個表中,pivot放在最終位置,這是一趟快排。
而後分別遞歸的對兩個子表重複上述過程,直至每部分內只有一個元素或空爲止,即所有元素放在了其最終位置上。
//快速排序:low=0,high=strlen(a)-1
int Partition(int a[],int low,int high){
int pivot=a[low];//將第一個記錄設爲樞軸
while(low<high){//循環跳出條件
while(low<high&&a[high]>=pivot) --high;
a[low]=a[high];//將比數軸值小的元素移動到左端
while(low<high&&a[low]<=pivot) ++low;
a[high]=a[low];//將比數軸值大的元素移動到右端
}
a[low]=pivot;//將數軸值插入最終位置
return low;//返回存放數軸的最終位置
}
void QuickSort(int a[],int low,int high) {
if(low<high){//遞歸跳出條件
int pivotpos=Partition(a,low,high);//劃分
QuickSort(a,low,pivotpos-1);//對兩個子表遞歸排序
QuickSort(a,pivotpos+1,high);
}
}