Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

merge sort and index out of bounds exception

801444Oct 11 2009 — edited Oct 12 2009
I'm trying to write a merge sort to sort in reverse order using an ArrayList, but I'm getting an IndexOutOfBounds exception and I don't see why.

Here's the code:
public class Junk {
	public static void main(String[] args){
		ArrayList<Integer> al=new ArrayList<Integer>();
		for(int x=0;x<10;x++){
			al.add(x);
		}
		sortBags(al,0,al.size());
		for(int x=0;x<al.size();x++){
			System.out.println(al.get(x));
		}
	}
	public static void sortBags(ArrayList<Integer> bagList,int start, int end){ 
		if(start<end){
			int mid=(int) Math.floor((start+end)/2);
			sortBags(bagList,start,mid);
			sortBags(bagList,mid+1,end);
			mergeBags(bagList,start,mid,end);
		}
	}
	
	public static void mergeBags(ArrayList<Integer> bagList,int start,int mid, int end){
		int l=mid-start;
		int r=end-mid;
		ArrayList<Integer> left=new ArrayList<Integer>();
		ArrayList<Integer> right=new ArrayList<Integer>();
		for(int x=0;x<l;x++){
			left.add(bagList.get(start+x));
		}
		for(int x=0;x<r;x++){
			right.add(bagList.get(x+mid));
		}
		left.add(Integer.MAX_VALUE);
		right.add(Integer.MAX_VALUE);
		bagList=new ArrayList<Integer>();
		int li=0;
		int ri=0;
		for(int x=start;x<end;x++){
			if(left.get(li)<=right.get(ri)){
				bagList.add(right.get(ri));
				ri++;
			}else{
				bagList.add(left.get(li));
				li++;
			}
		}
	}
}
Thank you.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 9 2009
Added on Oct 11 2009
12 comments
1,501 views