欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

合并已排序的数组(java)

程序员文章站 2022-07-14 21:41:04
...
  int[] a = { 1, 3, 5, 7, 9,11 ,12};
        int[] b = { 2, 3, 4, 6, 8, 10,33 };
        int[] c=new int[a.length+b.length];
        int temp=0;
        int aindex = 0;
        int bindex = 0;
        while (aindex < a.length && bindex < b.length) {
            if (a[aindex] == b[bindex]) {
                System.out.print(a[aindex]+" "+b[bindex]+" ");
                c[temp++]=a[aindex];
                c[temp++]=b[bindex];
                aindex++;
                bindex++;
            } else if (a[aindex] < b[bindex]) {
                System.out.print(a[aindex]+" ");
                c[temp++]=a[aindex];
                aindex++;
            } else {
                System.out.print(b[bindex] + " ");
                 c[temp++]=b[bindex];
                bindex++;
            }
        }
        while (aindex<a.length){
            System.out.print(a[aindex] + " ");
              c[temp++]=a[aindex];
            aindex++;
        }
        while (bindex<b.length){
            System.out.print(b[aindex] + " ");
              c[temp++]=b[bindex];
            bindex++;
        }
        System.out.println("\n"+Arrays.toString(c));

相关标签: java