Merging two ordered sequence is an ordered sequence

Ideas:

  • And merge the idea, in each case taking an element from two sequences are compared, the new sequence is added to the smaller, and finally the remainder of the sequence is copied directly into the new

Implementation code:


import java.util.Arrays;

// 合并两个有序序列为一个有序序列(归并的思想)
// 每次从两个序列中取出一个元素进行关键字的比较,将较小者放入c[ ]中,最后将各序列余下的部分直接复制到c[ ]中

public class MergeTwoSequence {
    public static void main(String[] args) {
        int[] a = {12, 45, 67, 90, 101};  // 有序表a
        int[] b = {2, 7, 52, 58, 89, 95}; // 有序表b
        int[] c = merge(a, b);
        System.out.println("合并后的有序序列:"+Arrays.toString(c));
    }

    public static int[] merge(int[] a, int[] b){
        int m = a.length;
        int n = b.length;
        int[] c = new int[m+n];
        int i = 0, j = 0, k = 0;
        while(i<m && j<n){
          if(a[i] <= b[j]){
              c[k++] = a[i++];
          }else{
              c[k++] = b[j++];
          }
        }
        while(i<m){
            c[k++] = a[i++];
        }
        while(j<n){
            c[k++] = b[j++];
        }
        return c;
    }
}

operation result:

Guess you like

Origin www.cnblogs.com/paopaolx/p/11335098.html