I have a simple recursive merge sort, I am just try to sort an array list of Integers that implement Comparable. I don't under stand why I am getting an error, when it runs it prints out the ArrayList of random Integers that I created and then it prints
no error yet
no error yet
Exception in thread "main" java.lang.StackOverflowError
and then it repeats
at MergeTemplate.rMerge(MergeTemplate.java:38)
a bunch of times until it finally says
Process complete
import java.util.*;
public class MergeTemplate{
private ArrayList <Comparable> temp1=new <Comparable> ArrayList();
int num;
Random ar=new Random();
public MergeTemplate(){
num=25;
}
public MergeTemplate(int n){
num=n;
}
public ArrayList <Comparable> fillArray(){
ArrayList <Comparable> ar1=new <Comparable> ArrayList();
for(int i=0;i<num; i++)
ar1.add(ar.nextInt(11));
screenOutput(ar1);
return ar1;
}
public void screenOutput(){
for(Comparable x: temp1)
System.out.print(x+ " ");
System.out.println();
}
public void screenOutput(ArrayList <Comparable> temp){
for(Comparable x: temp)
System.out.print(x+ " ");
System.out.println();
}
public void rMerge(ArrayList <Comparable> rList){
rMerge(rList, 0, rList.size()-1);
}
public void rMerge(ArrayList <Comparable> rList, int first, int last){
if (first-last==0){
System.out.println("no error yet");
}
else{
rMerge(rList, first, last/2);
rMerge(rList, last/2 + 1, last);
merge(rList, first, last);
}
}
public void merge(ArrayList <Comparable> a, int first, int last){
Comparable placeHolder;
if(a.get(first).compareTo(a.get(last))>1){
placeHolder=a.get(first);
a.set(first, a.get(last));
a.set(last, placeHolder);
}
}
}
public class Tester {
public static void main(String[] args) {
MergeTemplate one=new MergeTemplate(8);
one.rMerge(one.fillArray());
}
}