The line of code return tournamentTreeKSelection(listToArray(list), k);
is causing an infinite recursion in my program and I am unable to discover the exact cause.
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int tournamentTreeKSelection(int[] data, int k) {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>(list);
for(int i = 0; i < data.length - 1; i += 2) {
list.add(max(data[i] , data[i + 1]));
}
if(list.size() % 2 != 0) list.add(-1);
if(k > 1 && list.size() == 1) {
for(int i = 0; i < list2.size(); i++)
if(list2.get(i) == list.get(0))
list2.remove(i);
return tournamentTreeKSelection(listToArray(list2),--k);
}
if(list.size() == 1) return list.get(0);
return tournamentTreeKSelection(listToArray(list), k);
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] listToArray(ArrayList<Integer> arr) {
int[] arr2 = new int[arr.size()];
for(int i = 0; i < arr.size(); i++)
arr2[i] = arr.get(i);
return arr2;
}
}
I have done a hand trace using the array [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] and I am able to get down to a single element [10], why then is the run of the program causing a stack overflow ?