标签:
package sort; import java.util.Arrays; public class MergerSort { public static int arr1[]=new int[10]; public static int arr2[]=new int[10]; public static int arr3[]=new int[20]; static{ System.out.println("Before sort: "); System.out.print("arr1[]: "); for(int i=0;i<arr1.length;i++) arr1[i]=(int)(Math.random()*100); Arrays.sort(arr1); for(int i=0;i<arr1.length;i++) System.out.print(arr1[i]+" "); System.out.println(); System.out.print("arr2[]: "); for(int i=0;i<arr2.length;i++) arr2[i]=(int)(Math.random()*100); Arrays.sort(arr2); for(int i=0;i<arr2.length;i++) System.out.print(arr2[i]+" "); System.out.println(); } public static void main(String args[]){ System.out.println("After sort: "); mergerSort(); for(int i=0;i<arr3.length;i++) System.out.print(arr3[i]+" "); System.out.println(); } public static void mergerSort(){ int i1=0,i2=0; int k=0; while(i1<10 && i2<10){ if(arr1[i1]<=arr2[i2]){ arr3[k]=arr1[i1]; i1++; } else{ arr3[k]=arr2[i2]; i2++; } k++; } if(i1<10){ for(int j=i1;j<10;j++) arr3[k+j-i1]=arr1[j]; } if(i2<10){ for(int j=i2;j<10;j++) arr3[k+j-i2]=arr2[j]; } } }
标签:
原文地址:http://www.cnblogs.com/lvbubu/p/4695293.html