我有一个执行快速排序的应用程序。它工作得很好,直到我开始给它一些更大的数字(我第一次得到它是 10000000)。我知道 aStackoverflow
是由递归引起的,但我不明白为什么我的应用程序会因此而崩溃。任何意见,将不胜感激。这是我的代码:
class quickSort
{
const int NOOFELEMENTS = 10000000;
// this is our array to sort
private int[] arr = new int[NOOFELEMENTS];
// this holds a number of elements in array
private int len;
// Quick Sort Algorithm
public void QuickSort()
{
sort(0, len - 1);
}
public void sort(int left, int right)
{
int pivot, l_holder, r_holder;
l_holder = left;
r_holder = right;
pivot = arr[left];
while (left < right)
{
while ((arr[right] >= pivot) && (left < right))
{
right--;
}
if (left != right)
{
arr[left] = arr[right];
left++;
}
while ((arr[left] <= pivot) && (left < right))
{
left++;
}
if (left != right)
{
arr[right] = arr[left];
right--;
}
}
arr[left] = pivot;
pivot = left;
left = l_holder;
right = r_holder;
if (left < pivot)
{
sort(left, pivot - 1);
}
if (right > pivot)
{
sort(pivot + 1, right);
}
}
public static void Main()
{
quickSort q_Sort = new quickSort();
int[] arr = new int[NOOFELEMENTS];
Random rnd = new Random();
for (int i = 0; i < NOOFELEMENTS; i++)
{
arr[i] = rnd.Next(0, 1000);
}
q_Sort.arr = arr;
q_Sort.len = q_Sort.arr.Length;
var startTime = DateTime.Now;
// Sort the array
q_Sort.QuickSort();
Console.WriteLine("Total Time: {0}\n", DateTime.Now - startTime);
}
}