I am trying to write the code for quicksort but it keeps on going in infinte loop , I have tried hard to find the error in following code ,can anybody help please.
#include<stdio.h>
#include<stdlib.h>
int arr[100];
void quicksort(int low,int high)
{
int i = low,j = high,pivotIndex,pivot;
pivotIndex = rand()%20;
pivot = arr[pivotIndex];
if(i>=j)
return;
while(i<j)
{
while(arr[i]<pivot && i<j)
{
i++;
}
while(arr[j]>pivot && j>i)
{
j--;
}
if(i<j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
quicksort(low,i);
quicksort(i+1,high);
}
int main()
{
int i,j,temp;
for(i=0;i<20;i++)
arr[i] = rand()%21;
for(i=0;i<20;i++)
printf("%d ",arr[i]);
printf("\n");
quicksort(0,19);
for(i=0;i<20;i++)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
Your pivot selection is wrong, you should chose a pivot in (index) range
[low,high), while you chose a pivot in range[0,20):It will later make the partition not go well, and the value of
i, which you later use to recurse – will be wrong.EDIT:
One more issue is with the partitioning, it should also consider what to do with the pivot element and its duplicates – there should be some kind of “tie breaker” – the pivot should go to one side of the array (or some alternative).
For example, assume the pivot is
5and the array is[5,3,8,5]:You will just infinitely swap the 5’s over and over, which is definetly wrong.