【发布时间】:2016-02-04 16:52:09
【问题描述】:
我在 C 中实现了一个快速排序算法来对数组的元素进行排序。它适用于所有情况,除非数组具有两个或更多相等的元素。我一直在尝试修复它并一直在调试它,但是当有重复的元素时,我似乎无法让它工作。
对于如何更改我的代码以也适用于重复元素的任何帮助,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
//Random Array Length
#define L 10
#define MAX 100
void smarter_sort(int[],int,int);
void swap(int[],int,int);
int choose_piv(int[],int,int);
int main(){
int i, a[L];
//Generate an array of random numbers
for(i=0; i<L; i++)
a[i]= rand() % (MAX+1);
//Unsorted Array
printf("\nUnsorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
//Sorted Array
smarter_sort(a,0,L-1);
printf("\nSorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
return 0;
}
//Recursively defined quicksort (Pseudo-code listing 1.9)
void smarter_sort(int a[], int l, int r){
if(r > l){
int piv = choose_piv(a, l, r);
smarter_sort(a, l, piv-1);
smarter_sort(a, piv+1, r);
}
}
//Swap Elements
void swap(int a[], int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
//Choosing the pivot (pseudo-code listing 1.10)
int choose_piv(int a[], int l, int r){
//defining pointers and pivot
int pL = l, pR = r;
int piv = l;
while (pL < pR){
//finding the first left element greater than piv
while(a[pL] < a[piv])
pL++;
//finding the first right element greater than piv
while(a[pR] > a[piv])
pR--;
//swapping if the pointers do not overlap
if(pL < pR)
swap(a, pL, pR);
if(a[pL]==a[piv]||a[pR]==a[piv]){
pL++;
pR--;
}
}
//swapping and returning the rightmost pointer as the pivot
swap(a, piv, pR);
return pR;
}
【问题讨论】:
-
调试器是你的朋友。就像你在现实生活中的朋友一样,你必须付出一些努力才能保持这段关系的价值。
-
@mah,不。开个玩笑,我可以看到哪里出了问题,但我不知道我能做些什么来解决它:(