# Q：在快速排序算法，堆栈溢出异常

I am having a problem with my quicksort algorithm when trying to sort relatively big list that has no duplicates and are almost sorted (with only 5 numbers to sort).

`````` public static void MyQuickSort(List<int> list, int left, int right)
{
if (list == null || list.Count <= 1)
return;

if (left < right)
{
int pivotIdx = MyPartition(list, left, right);
//Console.WriteLine("MQS " + left + " " + right);
//DumpList(list);
MyQuickSort(list, left, pivotIdx - 1);
MyQuickSort(list, pivotIdx, right);
}
}

static int MyPartition(List<int> list, int left, int right)
{
int start = left;
int pivot = list[start];
left++;
right--;

while (true)
{
while (left <= right && list[left] <= pivot)
left++;

while (left <= right && list[right] > pivot)
right--;

if (left > right)
{
list[start] = list[left - 1];
list[left - 1] = pivot;

return left;
}

int temp = list[left];
list[left] = list[right];
list[right] = temp;

}
}
``````

`````` public static void MyQuickSort(List<int> list, int left, int right)
{
if (list == null || list.Count <= 1)
return;

if (left < right)
{
int pivotIdx = MyPartition(list, left, right);
//Console.WriteLine("MQS " + left + " " + right);
//DumpList(list);
MyQuickSort(list, left, pivotIdx - 1);
MyQuickSort(list, pivotIdx, right);
}
}

static int MyPartition(List<int> list, int left, int right)
{
int start = left;
int pivot = list[start];
left++;
right--;

while (true)
{
while (left <= right && list[left] <= pivot)
left++;

while (left <= right && list[right] > pivot)
right--;

if (left > right)
{
list[start] = list[left - 1];
list[left - 1] = pivot;

return left;
}

int temp = list[left];
list[left] = list[right];
list[right] = temp;

}
}
``````

Recursive algorithms are fun in academic exercises, but they're rarely used in practice, because of what you're seeing: too many recursive calls leads to excessive call stack usage, eventually terminating due to a stack overflow.