This is the 3-way quicksort…
private void quicksort3(int[] input, int low, int high)
{
int i = low - 1, j = high, left = low - 1, right = high, pivot = input[high], k;
if (high <= low) return;
while (true)
{
while (input[++i] < pivot) ;
while (pivot < input[--j])
if (j == low) break;
if (i >= j) break;
swap(input, i, j);
if (input[i] == pivot)
{
left++;
swap(input, left, i);
}
if (pivot == input[j]) {
right--;
swap(input, j, right);
}
}
swap(input, i, high); j = i - 1; i++;
for (k = low; k < left; k++, j--)
swap(input, k, j);
for (k = high - 1; k > right; k--, i++)
swap(input, i, k);
quicksort3(input, low, j);
quicksort3(input, i, high);
}
For input 9 5 3 I get exception error Index was outside the bounds of the array. the exception occurs here pivot = input[high] where the value of high is -1 (so I understand why I have error) but how I can fix it?
I call function like that quicksort3(arr,0,arr.Length-1);
Your value assignment is executed before the boundary condition is checked. So you should put
pivot = input[high]after lineif (high <= low) return;.