Merge Sorted Array

来源:互联网 发布:帝国cms官方网站 编辑:程序博客网 时间:2024/05/18 14:25

题目:

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 to hold additional elements from B. The number of elements initialized in A and B arem andn respectively.

代码如下:

void merge(int A[], int m, int B[], int n) {
        if(n==0)return;
        int index=m+n-1;
        int i=n-1,j=m-1;
        while(i>=0&&j>=0)
        {
            if(B[i]>A[j])
            {
                A[index--]=B[i--];
            }
            else
            {
                A[index--]=A[j--];
            }
        }
        while(i>=0)
        {
            A[index--]=B[i--];
        }
        return;
    }

原创粉丝点击