Skip to Main Content

New to Java

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!

Using a MergeSort with an Array List

807599Apr 15 2007 — edited Apr 15 2007
Hi. I'm working on a program that does a MergeSort using an array list. The user is asked to enter 2 arrays of increasing numbers, and my program will create a 3rd array that merges the 2 original ones.

I think I've almost got it down, but I seem to be running into an OutOfBounds error, and I'm not sure why. I've tried changing the initial values of some of my variables to no avail.

I'm kinda new to Java so be gentle.
import java.util.ArrayList;
import cs1.Keyboard;
import java.util.*;

public class MergeSort3
{
	public static void main (String[] args)
	{
		ArrayList<Integer> ary1 = new ArrayList<Integer>();
		ArrayList<Integer> ary2 = new ArrayList<Integer>();
		ArrayList<Integer> ary3 = new ArrayList<Integer>();
		
		
		
		int input=0, count=0, ary1count=0, ary2count=0, temp=0;
		boolean ok=true;
		
		while(ok)
		{
			System.out.println("Enter integers in Array1 from smallest to largest. (-1 to stop): ");
			input = Keyboard.readInt();
			if(input==-1)
				ok=false;
			else
				ary1.add(input);
			
		}
				
		ok=true;
		
		while(ok)
		{
			System.out.println("Enter integers in Array2 from smallest to largest. (-1 to stop): ");
			input = Keyboard.readInt();
			if(input==-1)
				ok=false;
			else
				ary2.add(input);
			
		}
						
		System.out.println("Size of array 1: "  + ary1.size());
		System.out.println("Size of array 2: "  + ary2.size());
		int ary3size=ary1.size()+ary2.size();
		
		System.out.println(ary3size);
				
		while(count<ary3size)
		{
			if(ary1.get(ary1count)<=ary2.get(ary2count) && ary1count<ary1.size() && ary2count<ary2.size())
			{
				
				ary3.add(ary1.get(ary1count));
				
				ary1count++;
				count++;
				System.out.println(ary3);
			}
			else
			{
				temp=ary2.get(ary2count);
				ary3.add(temp);
				ary2count++;
				temp=0;
				count++;
			}
			while(ary1count>=ary1.size() && ary2count<ary2.size())
			{
				ary3.add(ary2.get(ary2count));
				ary2count++;
			}
		}
		
		System.out.println(ary3);
		
		
		
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 13 2007
Added on Apr 15 2007
1 comment
175 views