I’m trying to use quick sort for my project but it doesn’t work. And I can’t figure out where the bug is. Anyone who can help me figure it out? Thank you.
void quicksort(int arr[],int a, int b){
if(a<=b){
int key=arr[a];
int index=a;
int i=a, j=b;
while(i<=j){
for(;arr[j]>key;--j);
int temp=arr[j];
arr[j]=key;
arr[index]=temp;
index=j;
for(;arr[i]<key;++i);
temp=arr[i];
arr[i]=key;
arr[index]=temp;
index=i;
}
quicksort(arr,a,index);
quicksort(arr,index,b);
}
else return;
}
Your inner loop does this:
key.key, located atindexand updateindextokey‘s new locationkey.key, located atindexand updateindextokey‘s new locationWhy in the world would you want to do this? You should do this:
key.key.I’m not 100% sure, but I think that shuffling the
keyaround in your version of quicksort may be the culprit of your problem. The best way to find out is to debug your code step by step and see where it goes wrong.Here’s the implementation according to my suggestion above, together with a few test-cases: