how to merge two sorted integer array in place using O(n) time and O(1) space cost

前端 未结 6 647
我在风中等你
我在风中等你 2020-12-01 04:38

For example, given an integer array and its two consecutive sequence \'s beginning position which are \'b1\' and \'b2\', furthermore provided with the position \'last\' whic

6条回答
  •  庸人自扰
    2020-12-01 05:04

    Here is O(n-1) Memory (n+1)

    /**
     * Created by deian on 2016-12-22.
     * We just need track the two smallest numbers 
     */
    public class Merge {
        public static void swap(int[] a, int i1, int i2) {
            int t = a[i1];
            a[i1] = a[i2];
            a[i2] = t;
        }
    
        public static void merge(int[] a) {
            // i1 and i2 - always point to the smallest known numbers
            // it would works as well with two m and n sized arrays 
            int i1 = 0;
            int i2 = a.length / 2;
    
            System.out.printf("    %s,      i(%d,%d)       \n", Arrays.toString(a), i1, i2);
            for (int di = 0; di < a.length - 1; di++) {
                int ni;
                int oi1 = i1; int oi2 = i2;
                if (a[i1] > a[i2]) {
                    ni = i2; i2++;
                    if (i2 >= a.length) { i2--; }
                } else {
                    ni = i1; i1++;
                    if (i1 >= i2) { i1 = di; }
                }
                if (di == i1) { i1 = ni; }
                swap(a, di, ni);
                System.out.printf("#%d: %s, i(%d,%d)s(%d>%d)i(%d,%d) \n", di + 1, Arrays.toString(a), oi1, oi2, ni, di, i1, i2);
            }
            System.out.printf("    %s\n", Arrays.toString(a));
        }
    
        public static void main(String[] args) {
    //        int[] a = new int[]{1, 3, 6, 8, -5, -2, 3, 8};
    //        int[] a = new int[]{1, 3, 6, 8, -5, 2, 3, 8};
    //        int[] a = new int[]{1, 5, 6, 8, -5, 2, 3, 4};
    //        int[] a = new int[]{1, 5, 6, 8, -5, -2, -1, 4};
    //        int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8};
    //        int[] a = new int[]{5, 6, 7, 8, 1, 2, 3, 4};
            int[] a = new int[]{1, 3, 5, 7, 2, 4, 6, 8};
            merge(a);
        }
    }
    

提交回复
热议问题