将两个有序的数组合并成一个有序的数组

此处提供两种方法

亲测,当数组数据量达到10000的时候,第一种方法的速度是第二种方法速度的130倍左右

第一种方法:

private int[] mergeArray(int[] a, int[] b) {
    int[] c = new int[a.length + b.length];
    int i = 0;
    int j = 0;
    int k = 0;
    while(i < a.length && j < b.length) {
        if (a[i] < b[j]) {
            c[k] = a[i];
            i ++;
        } else {
            c[k] = b[j];
            j ++;
        }
        k ++;
    }
    if (i == a.length && j < b.length) {
        for(int x = j; x < b.length; x ++) {
            c[k] = b[x];
            k ++;
        }
    }
    if (i < a.length && j == b.length) {
        for(int x = i; x < a.length; x ++) {
            c[k] = a[x];
            k ++;
        }
    }
    return c;
}

第二种方法(冒泡排序思想):

private int[] mergeArray(int[] a, int[] b) {
    int[] c = new int[a.length + b.length];
    
    for (int i = 0; i < a.length; i ++) {
        c[i] = a[i];
    }
    
    for (int i = 0; i < b.length; i ++) {
        int temp = b[i];
        for (int j = 0; j < a.length + i; j ++) {
            if (temp < c[j]) {
                //这样交换两个元素效率较高
                temp = temp ^ c[j];
                c[j] = temp ^ c[j];
                temp = temp ^ c[j];
            }
        }
        c[a.length + i] = temp;
    }
    return c;
}

猜你喜欢

转载自blog.csdn.net/u012131610/article/details/87094087