I have written following quick sort algorithm .But it's throwing the stack overflow exception. Any suggestion on how to fix this ..
static void Main(string[] args)
{
int[] input={17,12,6,19,23,8,5,10};
QuickSort(input,0,7);
foreach (int item in input)
{
Console.WriteLine(item);
}
}
static void QuickSort(int[] input,int p , int r)
{
if (p<r)
{
int q=Partition(input, p, r);
QuickSort(input, p, q );
QuickSort(input, q, r);
}
}
static int Partition(int [] input,int p,int r)
{
int pivot = input[r];//pivot element
int i = p - 1;
int j = r + 1;
while (true)
{
do
{
i = i + 1;
} while (!(input[i]>=pivot));
do
{
j = j - 1;
} while (!(input[j] <= pivot));
//swap
if (i<j)
{
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
else
{
return j;
}
}
}
p,qandrchange as you make the recursive call. Based on the error I'd guess they're not changing as they should.QuickSort(input, p, q ); QuickSort(input, q, r);looks suspicious to me. There should be either a q-1 or a q+1.