I am trying to test the time efficiency of the binary search for large sorted arrays in java.
This is the binary search method I am using, which takes in the search key and the array.
public int binarySearch(int[] a, int k) {
int l = 0;
int r = a.length - 1;
int m = 0;
while (l <= r) {
m = (l+r)/2;
if (k == a[m]) {
return m;
}
else if (k < a[m]) {
r = m - 1;
}
else {
l = m + 1;
}
}
return -1;
}
I think creating the array programmatically might cause an overhead in the efficiency. Therefore I am trying to initialize large arrays as constant and use it in the program.
I tried both Array and ArrayList as shown below.
public static int D10000[] = {0, 1, 2, 3, ..... 10000};
public static ArrayList<Integer> D10000 = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, ...... 10000);
I am getting the following compilation error because the array size is too big.
Information:java: The system is out of resources.
Information:java: Consult the following stack trace for details.
Information:java: at com.sun.tools.javac.code.Type.map(Type.java:220)
Information:java: Errors occurred while compiling module 'SearchAlgo'
Information:javac 1.8.0_144 was used to compile java sources
Information:21/10/17, 12:02 PM - Compilation completed with 1 error and 0 warnings in 1s 481ms
Error:java: java.lang.StackOverflowError
What is the best approach in achieving this?