您好,登錄后才能下訂單哦!
快速排序的多種思路實現:
兩邊想中間靠攏:
// 兩邊想中間靠攏,當a[left]<key a[right]>key時,兩者交換 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 時 將a[left]放到right位置,a[right]<key時,將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從左向右走,當a[left]<key時,left停止,當a[right]>key,right停止,交換兩者對應的值 int PartSortBothRight(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int prev = left; while (a[left] < key)//當開始的數字比key小移動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; }
調用函數:
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 };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。