您好,登錄后才能下訂單哦!
快速排序的多種思路實(shí)現(xiàn):
兩邊想中間靠攏:
// 兩邊想中間靠攏,當(dāng)a[left]<key a[right]>key時(shí),兩者交換 int PartSortBothSize(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int begin = left; int end = right - 1; while (begin < end) { while (begin<end && (a[begin]<=key)) { ++begin; } while (begin<end&&(a[end]>=key)) { --end; } if (begin < end) { swap(a[begin], a[end]); } } if (a[begin]>a[right]) { swap(a[begin], a[right]); return begin; } return right; }
挖坑法:
// 挖坑法left right是坑 a[left]>key 時(shí) 將a[left]放到right位置,a[right]<key時(shí),將a[right]放到left位置 int PartSortPotholing(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int begin = left; int end = right; while (left<right) { while (left<right&&a[left] <= key) { left++; } if (left < right) { a[right] = a[left]; right--; } while (left<right&&a[right] >= key) { right--; } if (left < right) { a[left] = a[right]; left++; } } a[left] = key; return left; }
順向
//順向 //left、right從左向右走,當(dāng)a[left]<key時(shí),left停止,當(dāng)a[right]>key,right停止,交換兩者對(duì)應(yīng)的值 int PartSortBothRight(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int prev = left; while (a[left] < key)//當(dāng)開始的數(shù)字比key小移動(dòng)left、prev { left++; prev++; } while (left < right) { while (left < right&&a[left] >= key) { left++; } while (left < right&&a[prev] <= key) { prev++; } if (left < right) { swap(a[left], a[prev]); left++; prev++; } } swap(a[prev], a[left]); return prev; }
調(diào)用函數(shù):
void _QuickSort(int *a, int left,int right) { assert(a != NULL); if (left >= right) { return; } //int div = PartSortBothSize(a, left, right); //int div = PartSortPotholing(a, left, right); int div = PartSortBothRight(a, left, right); if (div > 0) { _QuickSort(a, left, div - 1); } if (div < right - 1) { _QuickSort(a, div + 1, right); } } void QuickSort(int *a, size_t size) { assert(a != NULL); if (size > 1) { _QuickSort(a, 0, size - 1); } }
test:
int a4[] = { 0, 5, 2, 1, 5, 5, 7, 8, 5, 6, 9, 4, 3, 5, -2, -4, -1 };
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。