问题描述:两个有序数组,一个长度为m,一个长度为n,需要将两个数组合并成一个数组
思路:
首先想到了二路归并,难点在于判断两路谁现被耗尽,未被耗尽的一个将会被依次添加数组
代码测试:
ps:这是第一次的想法,最真实的水平
import java.util.Scanner;
public class MergeSort { public static void main(String[] args) { Scanner p1 = new Scanner(System.in); System.out.println("输入第一个数组,数组长度为m=:"); int m = p1.nextInt(); int[] a = new int[m]; for(int i = 0;i < m;++i){ System.out.println("输入第"+(i+1)+"个数:"); a[i] = p1.nextInt(); } Scanner p2 = new Scanner(System.in); System.out.println("输入第二个数组,数组长度为n=:"); int n = p2.nextInt(); int[] b= new int[n]; for(int j = 0;j < n;++j){ System.out.println("输入第"+(j+1)+"个数:"); b[j] = p2.nextInt(); } int[] c = new int[a.length + b.length]; int t=0; int f=0; int k=0; while(t<a.length&& f<b.length){ if(a[t]<b[f]){ c[k++]= c[t++]; }else{ c[k++]=b[f++]; } } while(t<m) { c[k++]=a[t++]; } while(f<n) { c[k++]=b[f++]; } for (int x:c) { System.out.print(x+",\t"); } } }-----------------------------------------------------------------------------------------
改进后的代码 利用方法,看起来更简洁了
public class MergeApp {
public static void merge(int[] arrayA,int sizeA,int[] arrayB,int sizeB,int[] arrayC){ int aDex = 0,bDex = 0,cDex = 0; while (aDex < sizeA && bDex < sizeB){ if (arrayA[aDex] < arrayB[bDex]){ arrayC[cDex++] = arrayA[aDex++]; }else{ arrayC[cDex++] = arrayB[bDex++]; } } while (aDex < sizeA){ arrayC[cDex++] = arrayA[aDex++]; } while (bDex < sizeB){ arrayC[cDex++] = arrayB[bDex++]; } } public static void display(int[] theArray,int size){ for (int i = 0; i < size; i++) { System.out.print(theArray[i] + " "); } System.out.println(""); } public static void main(String[] args) { int[] arrayA = {23,47,81,95}; int[] arrayB = {7,14,39,59,62,74}; int[] arrayC = new int[10]; merge(arrayA, 4, arrayB, 6, arrayC); display(arrayC,10); } }---------------------------------------------------
代码升级
ps:更优雅了,有木有
public class MergeSortss {
public static void merge(int[] A,int m,int[] B,int n,int[] arrayC){ int i = 0,j = 0,k = 0; while(k<(m+n)) { if(j==n||(i<m&&A[i]<B[j])) { arrayC[k++]=A[i++]; } else { arrayC[k++]=B[j++]; } } } public static void display(int[] theArray,int x){ for (int i = 0; i < x; i++) { System.out.print(theArray[i] + " "); } System.out.println(""); } public static void main(String[] args) { int[] A = {14,23,95}; int[] B = {1,7,39,59,62,74}; int[] C = new int[10]; merge(A, 3, B, 6, C); display(C,9); } }