I'm trying to implement the quicksort algorithm (in C#),here's my code:
public static void sort(ref int[] A)
{
if (A.Length==0 || A.Length==1)
{
return;
}
quickSort(ref A,0,A.Length-1);
}
private static void quickSort(ref int[] A, int left, int right)
{
if (left >= right || left < 0 || right < 0)
return;
int pivot = A[left];
int i = left - 1;
int j = right + 1;
while (true)
{
do
{
i++;
}
while (A[i] < pivot);
do
{
j--;
}
while (A[j] > pivot);
if (i >= j)
break;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
quickSort(ref A,left,j);
quickSort(ref A, j + 1, right);
}
This algorithm works fine, however something seems illogical, I chose pivot to be equal to A[left] then in the while(true) loop I wrote do{i++}while(A[i]<pivot), I now noticed that the first time it's going to increment i so A[i] will become equal to A[left] which is the pivot value, so that should mean this do while loop will stop after the first increment of i, so when I tried to add the = operator to the while so that it won't stop after the first increment: while(A[i]<=) I got a stack overflow exception (also got the stack overflow exception when I added the equal operator to the the 2nd do while: while(A[j]>=pivot)), and I can't understand why this happened, anyone can explain please?
refis unnecessary, since you never assign to the variableA. (refaffects variables, not values.)=operator to 1 of the twowhileinside thewhile(true)that it stops working and give me a stack overflow exception