Java Programming. Write your own source code with plenty of comments. Chapter 7
ID: 3793034 • Letter: J
Question
Java Programming. Write your own source code with plenty of comments.
Chapter 7 Exercise 31, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.
7.31 (Merge two sorted lists) Write the following method that 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 at most 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 the elements in the list. This number is not part of 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
Explanation / Answer
Please find my code.
please let me know in case of any issue.
import java.util.Scanner;
public class MergeSortedArray {
public static int[] merge(int[] list1, int[] list2){
int[] answer = new int[list1.length + list2.length];
int i = 0, j = 0, k = 0;
while (i < list1.length && j < list2.length)
answer[k++] = list1[i] < list2[j] ? list1[i++] : list2[j++];
while (i < list1.length)
answer[k++] = list1[i++];
while (j < list2.length)
answer[k++] = list2[j++];
return answer;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Length of list1: ");
int n1 = sc.nextInt();
int[] list1 = new int[n1];
System.out.print("Enter list1: ");
for(int i=0; i<n1; i++)
list1[i] = sc.nextInt();
System.out.print("Length of list2: ");
int n2 = sc.nextInt();
int[] list2 = new int[n2];
System.out.print("Enter list2: ");
for(int i=0; i<n2; i++)
list2[i] = sc.nextInt();
int[] list3 = merge(list1, list2);
System.out.print("The merged list: ");
for(int i=0; i<list3.length; i++)
System.out.print(list3[i]+" ");
System.out.println();
}
}
/*
Sample run:
Length of list1: 5
Enter list1: 1 6 7 12 13
Length of list2: 4
Enter list2: 3 10 22 23
The merged list: 1 3 6 7 10 12 13 22 23
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.