[问题] 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