Merge Sorted Array

每日一题,最近开题,少写了几次~

今天做的是合并有序数组。做了三种方法:

1、先把B加到A的尾部,然后快排出来的结果。

2、新建一个数组,先把A全部复制进去,然后开始拿,克隆A里面最小的,B里面最小的,按照顺序往A里面放。

3、移动,(类似于插入排序的思想),把B里面的数一个一个拿出来,然后在A中找到它的位置,后面所有元素往后挪动一位。


前两种都是197ms;第三种是196ms。其实都差不多。

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * Created by Mary on 15-1-6.
 */
public class MergeStoreArray {
    public static void merge1(int A[], int m, int B[], int n) {
        for(int i = 0;i<n;i++){
            A[m+i] = B[n-i-1];
        }
        sort(A,0,m+n-1);
    }

    private static void sort(int[] array,int low,int high){
        if(low>= high){
            return;
        }
        int first = low;
        int last = high;
        int key = array[low];
        while (first<last){
            while (first<last && array[last]>=key)
                --last;
            array[first] = array[last];
            while (first<last && array[first]<=key)
                ++first;
            array[last] = array[first];
        }
        array[first] = key;
        sort(array, low, first-1);
        sort(array, first+1, high);
    }

    public static void merge2(int A[], int m, int B[], int n) {
        int[] C = new int[m];
        System.arraycopy(A,0,C,0,m);
        int i = 0;int j = 0;int d = 0;
        while (i<m&&j<n){
            if(C[i]<B[j]){
                A[d]=C[i];
                i++;
                d++;
                continue;
            }else if(C[i] > B[j]){
                A[d] = B[j];
                j++;d++;
                continue;
            }else {
                A[d] = C[i];
                d++;
                A[d] = B[j];
                d++;
                i++;j++;
            }
        }
        if(i<m){
            for(int t = i;t<m;t++){
                A[d] = C[t];
                d++;
            }
        }
        if(j<n){
            for(int t = j;t<n;t++){
                A[d] = B[t];
                d++;
            }
        }

    }

    public static void merge(int A[], int m, int B[], int n) {
        int i=0;
        for(int j = 0;j<n;j++){
            while (A[i]<B[j] && i<m+j)
                i++;
            for(int t=m+j;t>i;t--){
                A[t] = A[t-1];
            }
            A[i]=B[j];
            i++;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值