Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just need some help starting this. I guess my main question is how can write it so the first number entered is the length of the list. Here his the outline of the project below.....


Write the following method the merges two sorted lists into a new sorted list.

public static int[] merge(int[] list1, int[] list2)

Implement the method in a way that takes list1.length + list2.length comparisons. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of elements in the list.

Enter list1: 5 1 5 16 61 111
Enter list2: 4 2 4 5 6
The merged list is: 1 2 4 5 5 6 16 61 111

What I have tried:

I know how to create a array of user determined size but I only know how to do that using two inputs, not all in one array input statement. I'm just very confused. any help?
Posted
Updated 7-Dec-17 5:45am
Comments
Patrice T 7-Dec-17 13:11pm    
What is your code so far.

Your method takes two arrays - so get the length of both, and add them together.
Declare an array of that size.
Now set up two indexes: i1 and i2, and set them both to zero.
Start a loop:
if list1[i1] <= list2[i2] then add list1[i1] to the output and increment i1
otherwise add list2[i2] to the output and increment i2
continue to loop until i1 or i2 runs out of elements.
Add the remaining elements to the output.

Return the output.
 
Share this answer
 
v2
Comments
CPallini 7-Dec-17 11:44am    
5.
Quote:
I know how to create a array of user determined size but I only know how to do that using two inputs, not all in one array input statement. I'm just very confused. any help?
Here you are the code for reading a input line and store the integers in a array:
Java
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int [] a = new int [n];
for (int i=0; i<n; ++i)
  a[i] = s.nextInt();


Then follow Griff's suggestions.
 
Share this answer
 
v2
Comments
OriginalGriff 7-Dec-17 11:53am    
Are you getting a lot of hamsters this afternoon? Because I am - I saw you had two identical answers here and deleted one. Bingo! Hamsters embedded in the page (presumably an Ajax area).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900