快速排序用到了分治班利、和遞歸的思想,感覺挺有趣盐固。
基本算法:
1).選擇一個基準元素,通常選擇第一個元素丈挟。
2).通過一趟排序?qū)⒋判虻挠涗浄指畛瑟毩⒌膬刹糠值蟛罚渲幸徊糠钟涗浀脑刂稻然鶞试刂敌?"左子樹"。另一部分記錄的元素值比基準值大 "右子樹"曙咽。
3).此時基準元素在其排好序后的正確位置,"樹的根節(jié)點"蛔趴。
4).然后分別對 左子樹和右子樹進行同樣的排序操作,直到整個序列有序例朱。
void swap_1_1(int *a,int *b){
*a^=*b^=*a^=*b;
}
//獲得中軸的位置
//升序排序
int partition_1_1(int a[],int low ,int high){
//假定基數(shù)是a[low]
int privotkey = a[low];
while (low < high) {
while (low < high &&a[high]>= privotkey) {
high --;
}
if (a[low] >a[high]) {
swap_1_1(&a[low], &a[high]);//將左邊比右邊大的記錄交換
}
while (low < high&&a[low] <= privotkey) {
low++;
}
if (a[low] > a[high]) {
swap_1_1(&a[low], &a[high]);//將左邊比右邊大的記錄交換
}
}
//外層的low = high 時退出孝情,但是起初進入函數(shù)時 low < high,過程中,high必定自減洒嗤,或者low自加 即操作Operation1 = high--,Operation2 = low++; 邏輯表達式(Operation1||Operation2)必定是YES
return low;
}
void quickSort1_1(int a[],int low,int high){
if (low < high) {
//獲得中軸位置
int privotLocition = partition_1_1(a,low,high);//將主樹劃分成箫荡,左子樹和右子樹,樹的根節(jié)點即中軸的元素渔隶,左子樹的所有值羔挡,小于右子樹的所有值
quickSort1_1(a,0,privotLocition-1);//對左子樹繼續(xù)劃分
quickSort1_1(a,privotLocition+1, high);//對右子樹繼續(xù)劃分
}
}
主函數(shù)調(diào)用
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int a[5] = {3,1,5,7,8};
printf("初始值");
print(a,5);
quickSort1_1(a,0,4);
printf("\n結果\n");
print(a,5);
}
return 0;
}