StackOverflowError Java

edited September 2007 in Science & Tech
Hey, I'm making a mergesort program in java and i ran into a error i cant seem to fix.[PHP]import java.util.ArrayList;

public class APMergeSort
{ public static ArrayList<Comparable> mergesort(ArrayList<Comparable> a1)
{ if (a1.size() == 1)
{ return a1;
}
else
{ ArrayList<Comparable> left = new ArrayList<Comparable>(a1.size()/2);
for(int x = 0; x < a1.size()/2; x++)
{ left.add(a1.get(x));
}
ArrayList<Comparable> right = new ArrayList<Comparable>((a1.size()/2) + 1);
for(int x = 0; x < (a1.size()/2) + 1; x++)
{ right.add(a1.get(x));
}
left = mergesort(left);
right = mergesort(right);
merge(left, right, a1);
return a1;
}
}
public static ArrayList<Comparable> merge(ArrayList<Comparable> a1, ArrayList<Comparable> left, ArrayList<Comparable> right)
{ int lindex = 0;
int rindex = 0;
int index = 0;
while (lindex < left.size() && rindex < right.size())
{ if (left.get(lindex).compareTo(right.get(rindex)) < 0)
{ a1.add(index, left.get(lindex));
lindex++;
}
else
{ a1.add(index, right.get(rindex));
rindex++;
}
index++;
}

ArrayList<Comparable> zxc = new ArrayList<Comparable>();
int zxcindex;
if (lindex >= left.size())
{ for(int x = 0; x < right.size(); x++)
{ zxc.add(right.get(x));
}
zxcindex = rindex;
}
else
{ for(int x = 0; x < left.size(); x++)
{ zxc.add(left.get(x));
}
zxcindex = lindex;
}
for (int x = zxcindex; x < zxc.size(); x++)
{ a1.add(index, zxc.get(x));
index++;
}
return a1;
}
}
[/PHP]

The StackOverflowErrors were at
[PHP]ArrayList<Comparable> left = new ArrayList<Comparable>(a1.size()/2);[/PHP]
&
[PHP]right = mergesort(right);[/PHP]

can Someone help me out.

*Note:my main method is in another class ALSO a1 is the arraylist where the initial objects are entered*

Comments

  • broady81broady81 Member
    edited September 2007
    Being relatively new to Java (1 year), I believe a Stack Overflow Error is when you have a value that reoccurs infinitely (e.g. a loop that uses all available memory). Looking at your code, I would suggest looking at the loop in the first "if" statement <code style="white-space: nowrap;"><code></code></code>as I think it is creating a repeating instance of itself - Just an idea :rolleyes2
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited September 2007
    are you calling merge correctly?

    <code style="white-space: nowrap;"><code>merge(ArrayList<Comparable> a1, ArrayList<Comparable> left, ArrayList<Comparable> right)
    </code></code>
    you're calling merge(left,right,a1);<code style="white-space: nowrap;"><code></code></code>
  • edited September 2007
    thanx for all the advice, especially the catch on how i called it.
Sign In or Register to comment.