I'm implementing Quick sort algorithm in C#. Implementation as follow:
/// <summary>
/// Perform Sort
/// </summary>
/// <returns></returns>
public override List<int> Sort(List<int> list)
{
try
{
this.quick(ref list, 0, list.Count - 1);
return list;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Quick sort main algorithm
/// </summary>
/// <param name="list"></param>
/// <param name="left"></param>
/// <param name="right"></param>
private void quick(ref List<int> list, int left, int right)
{
try
{
int i, j;
int x, y;
i = left;
j = right;
x = list[left];
do
{
while (list[i] < x && i < right)
{
i++;
}
while (list[j] > x && j > left)
{
j--;
}
if (i <= j)
{
y = list[i];
list[i] = list[j];
list[j] = y;
i++;
j--;
}
}
while (i <= j);
if (left < j)
{
this.quick(ref list, left, j);
}
if (i < right)
{
this.quick(ref list, i, right);
}
}
catch (Exception)
{
throw;
}
}
If I call Sort and pass in an unordered list, it works ok. But if I pass in an ordered list, a StackOverflowException occur. I tried to figure out why is it but still have no clue. So please point out for me what wrong did I do.
Update
I found the cause of error: at the first recursion, the algorithm set j = -1, so that i will never meet j, and led to StackOverflow. So how to get rid of this behavior? I mean is there anyway to figure out that the list that has been passed in is an ordered list and terminate the algorithm?
ordered list1, 5, 4and it worked fine.. then I passed in1,4,5and it was fine..