[問題] quicksort swap pivot時出現問題
完整程式碼:
#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的地方出問題,
但我怎麼看都看不出原因,
求各位大神指教,感謝~~
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.171.201.122
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1554731979.A.52E.html
※ 編輯: nasty1122 (118.171.201.122), 04/08/2019 22:03:55
※ 編輯: nasty1122 (118.171.201.122), 04/08/2019 22:04:35
※ 編輯: nasty1122 (118.171.201.122), 04/08/2019 22:05:30
推
04/08 22:24,
6年前
, 1F
04/08 22:24, 1F
推
04/08 22:54,
6年前
, 2F
04/08 22:54, 2F
→
04/08 22:58,
6年前
, 3F
04/08 22:58, 3F
但因為pivot是middle的話在迴圈內就會一直被換來換去,所以最後那邊不能寫arr
[(front+end)/2],有其他方式可以表示pivot最後在的位置嗎?
※ 編輯: nasty1122 (118.171.201.122), 04/08/2019 23:47:52
推
04/09 07:17,
6年前
, 4F
04/09 07:17, 4F
→
04/09 07:18,
6年前
, 5F
04/09 07:18, 5F
→
04/09 07:18,
6年前
, 6F
04/09 07:18, 6F
→
04/09 07:19,
6年前
, 7F
04/09 07:19, 7F
→
04/09 07:20,
6年前
, 8F
04/09 07:20, 8F
→
04/09 07:21,
6年前
, 9F
04/09 07:21, 9F
感謝回答,其實我原本寫的就是把pivot放最後的,這樣交換不會有問題沒錯,但就是想
試試看把pivot放中間,有沒有方法可以追蹤pivot最後換到的位子呢?
※ 編輯: nasty1122 (101.9.7.42), 04/09/2019 15:09:44
推
04/11 20:43,
6年前
, 10F
04/11 20:43, 10F
→
04/11 20:43,
6年前
, 11F
04/11 20:43, 11F
後來再加一個變數存pivot index就可以了,感謝你~~
※ 編輯: nasty1122 (115.82.133.211), 04/12/2019 12:59:23
※ 編輯: nasty1122 (101.8.162.223), 04/14/2019 13:08:51
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 3 篇):