Java Programming. Write your own source code with plenty of comments. (Merge two
ID: 3792918 • Letter: J
Question
Java Programming. Write your own source code with plenty of comments.
(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
import java.util.*;
public class P9_21 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter list1: ");
int n = input.nextInt();
int[] array1 = new int[n];
for(int i =0 ; i < n ; i++){
array1[i]=input.nextInt();
}
System.out.println("Enter list2: ");
int m = input.nextInt();
int[] array2 = new int[m];
for(int i =0 ; i < m ; i++){
array2[i]=input.nextInt();
}
display(merge(array1,array2));
}
public static int[] merge(int[] list1 , int[] list2){
int index = list1.length + list2.length;
int index1 =list1.length -1 ;
//System.out.println("marime l1 este "+list1.length);
int index2 = list2.length -1;
int[] marray = new int[list1.length + list2.length];
while(index >= 0){
while(index1 >= 0 && index2 >= 0){
index--;
if(list1[index1] > list2[index2]){
marray[index ]= list1[index1];
index1--; }
else if(list1[index1] == list2[index2]){
marray[index] = list1[index1];
index1--;
index-- ;
marray[index] = list2[index2];
index2--;
}
else {
marray[index ] = list2[index2];
index2--;
}
//System.out.println("index is "+index+" and array value is "+marray[index ]);
//System.out.println("index1 is "+index1+" and index2 is "+index2);
}
if(index1 > index2){
System.out.println("index1 is "+index1+" and index2 is "+index2);
for(int j = index1 ;j >= 0 ;j--){
index--;
marray[index] =list1[index1];
}
}
if(index1 < index2 ){
for(int j = index2 ;j >= 0 ;j--)
{
index--;
marray[index] =list2[index2];
}
}
}
//System.out.println(marray.length);
return marray;
}
public static void display(int[] array){
for(int i = 0 ; i < array.length ; i++){
System.out.print(array[i]+" ");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.