Click here to Skip to main content
13,406,567 members (41,581 online)
Rate this:
 
Please Sign up or sign in to vote.
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 7-Dec-17 5:44am
Updated 7-Dec-17 6:45am
Comments
ppolymorphe 7-Dec-17 13:11pm
   
What is your code so far.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
v2
Comments
CPallini 7-Dec-17 11:44am
   
5.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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:
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.
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.180221.1 | Last Updated 7 Dec 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100