#第七章第三十一题(合并两个有序列表)(Merge two ordered tables)
-
**7.31(合并两个有序列表)编写下面的方法,将两个有序列表变成一个新的有序列表。
public static int[] merge(int[] list1,int[] list2)
只进行list.length+list2.length次比较来实现该方法。该实现的动画演示参见。编写一个测试程序,提示用户输入两个有序列表,然后显示合并后的列表。下面是一个运行示例。注意,输入的第一个数字表示列表元素的个数。该数字不是列表的一部分。
Enter list1 size and contents:5 1 5 16 61 111
Enter list2 size and contents:4 2 4 5 6
1 2 4 5 5 6 16 61 111
*7.31(Merge two ordered tables)Write the following method to change two ordered tables into a new ordered list.
public static int[] merge(int[] list1,int[] list2)
Only list.length +List2. Length times to implement the method. Animation of the implementation [for demonstration, see]( http://liveexample.pearsoncmg.com/dsanimation/MergeSortNeweBook.html )。 Write a test program, prompt the user to input two sequential tables, and then display the merged list. Here is a running example. Note that the first number you enter represents the number of list elements. The number is not part of the list.
Enter list1 size and contents:5 1 5 16 61 111
Enter list2 size and contents:4 2 4 5 6
1 2 4 5 5 6 16 61 111 -
参考代码:
package chapter07; import java.util.Arrays; import java.util.Scanner; public class Code_31 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter list1 size and contents:"); int length1=input.nextInt(); int[] list1=new int[length1]; for(int i=0;i<list1.length;i++){ list1[i]=input.nextInt(); } System.out.print("Enter list2 size and contents:"); int length2=input.nextInt(); int[] list2=new int[length2]; for(int i=0;i<list2.length;i++){ list2[i]=input.nextInt(); } for(int i=0;i<merge(list1,list2).length;i++) System.out.print(merge(list1,list2)[i]+" "); } public static int[] merge(int[] list1,int[] list2){ int[] list3=new int[list1.length+list2.length]; for(int i=0;i<list1.length;i++){ list3[i]=list1[i]; } for(int i=list1.length,j=0;i<list1.length+list2.length;i++,j++){ if(j>list2.length) break; list3[i]=list2[j]; } Arrays.sort(list3); return list3; } }
-
结果显示:
Enter list1 size and contents:5 1 5 16 61 111 Enter list2 size and contents:4 2 4 5 6 1 2 4 5 5 6 16 61 111 Process finished with exit code 0