我正在尝试分析Java中针对不同大小为n的数组的Insertion Sort递归方法。它对于小数组大小排序很好,但是当我尝试测试它时,假设数组大小为32000,它会给我一个StackOverflowError。
有没有办法解决这个问题?我正在使用eclipse IDE。
我正在使用的递归算法如下:
...
@Override
public int[] recursiveSort(int[] list)
{
// Start the clock
this.startTime = System.nanoTime();
count = 0;
int n = list.length;
insertionSortRecursive(list, n);
// Stop the clock
this.stopTime = System.nanoTime();
return list;
}
// Recursive function to sort an array using insertion sort
static void insertionSortRecursive(int arr[], int n)
{
count++;
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive( arr, n - 1 );
// Insert last element at its correct position in sorted array.
int last = arr[n - 1];
int j = n - 2;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position.
while (j >= 0 && arr[j] > last)
{
count++;
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}