[問題] quicksort swap pivot時出現問題

作者: nasty1122 (阿寶)   2019-04-08 21:59:37
完整程式碼:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int Partition(int *arr, int front, int end){
int pivot = arr[(end+front)/2];
int i = front -1, j;
//i denotes the position of the key where all the elements in the front
are smaller than pivot.
for (j = front; j < end+1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
i++;
swap(&arr[i], &pivot); //put pivot into the middle of the two subarrays
return i;
}
void QuickSort(int *arr, int front, int end){
if (front < end) {
int p = Partition(arr, front, end);
QuickSort(arr, front, p - 1);
QuickSort(arr, p + 1, end);
}
}
int main() {
int n,i;
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
QuickSort(arr, 0, n-1);
for (i = 0; i < n; i++) {
printf("%d ",arr[i]);
}
return 0;
}
這是一個以array中間為pivot的quicksort,
第一個輸入的數字表示有幾個數字要排序,
但我的輸出結果卻是這樣:
假設輸入:10
4 8 7 2 3 5 6 9 10 1
輸出結果:
1 2 3 3 3 5 6 7 8 9 10
有些數字莫名其妙就被換掉了,
好像是在Partition迴圈結束那邊swap arr[i]跟pivot的地方出問題,
但我怎麼看都看不出原因,
求各位大神指教,感謝~~
作者: goddbird (上帝的鳥)   2019-04-11 20:43:00
其實在swap裡改成&arr[你的pivot_idx]就會對了吧?小弟也弱弱的還麻煩分享一下結果
作者: LPH66 (-6.2598534e+18f)   2019-04-08 22:24:00
因為你的那個對換不是陣列元素對換
作者: james80351   2019-04-08 22:54:00
那個地方是要和前面pivot代表的元素做交換arr[(front + end) / 2]
作者: LPH66 (-6.2598534e+18f)   2019-04-09 07:17:00
所以一個常見的方法其實是先把 pivot 放在陣列"開頭"接著用你的方法維護成 [pv][<pv ... <pv][>pv ... >pv]最後再用你這一步想做的交換把 [pv] 擺在兩塊中間概念上其實和你已經寫好的差不多, 只是不是另起變數存 pv重點在於這一步既然要是陣列元素對換, 那就把 pv 也擺進去定位問題就先找個好定位的地方放就好 (例如陣列開頭)

Links booklink

Contact Us: admin [ a t ] ucptt.com