I have written a small Java program implementing the bubble sort technique for int arrays. It works for arrays of 1000 units, but when I increase it to 10 000, it crashes with java.lang.StackOverflowError.
Here is the code:
import java.util.*;
import java.lang.*;
class BubbleSort
{
public static void main (String [] argv)
{
int Array [] = new int [10000];
for (int a = 0; a < 10001; a++)
{
Array[a] = (int) (Math.random()*100);
}
// generated an array of 10000 units and filled with random numbers
for (int end = Array.length-1; end >= 0; end--)
{
BubbleSort (Array, 0, end);
}
}
public static int BubbleSort (int A [], int count, int end)
{
if (count == end) //debugger says crash occurs here
{
return count;
}
else
{
if (A[count] > A[count+1])
{
int temp = A[count];
A[count] = A[count+1];
A[count+1] = temp;
return BubbleSort(A, count+1, end); //and here
}
else
{
return BubbleSort(A, count+1, end);
}
}
}
}
Any help very appreciated!
Keeping aside the logic, the technical reason as to why it fails at 10000
is because each thread in Java has a fixed stack size. And when you use 10000 it is unable to find enough memory.
Use -XX:ThreadStackSize=512
to increase the default memory that JVM allocates to threads and it may work. But generally you don't have to bother about it.
On a sidenote check whether you really require recursion over here.