两个已排序的数组进行合并

描述:

   该程序是按照从小到大的顺序进行排序,代码如下:

#include <iostream>
#include <assert.h>

/*
*Describe:print the elements of the array
*Data:5/11/2013
*Author:pjgan
*Version:1
*tool:vc++2008
*/
void Global_printElements(const int *pArray,int Array_Length);

/*
*Return: true is sorted
*
*/
bool Global_isSort(const int  *pArray, int iArrayLeng);

/*
*Return: is the returlts of the Merge Array_A and Array_B
*/
void *Global_Merge(const int *Array_A, int Array_A_Length, const int *Array_B, int Array_B_Length);

void Global_printElements(const int *pArray,int Array_Length){
    assert(pArray);
    int i = 0;
    for( ; i < Array_Length; ++i) {
        std::cout<<pArray[i]<<"   ";
    }
    std::cout<<std::endl;
}

bool Global_isSort(const int  *pArray, int iArrayLeng){
    assert(pArray);
    int i = 0;
    int j = 0;
    for( ; i < (iArrayLeng-1); ++i) {
        for( j = ( i + 1); j < iArrayLeng; ++j) {
            if(pArray[i] > pArray[j]) return false;
        }
    }
    return true;
}

void *Global_Merge(const int *Array_A, int Array_A_Length, const int *Array_B, int Array_B_Length) {
    assert(Array_A && Array_B);
    bool bArrayAisSorted = Global_isSort(Array_A, Array_A_Length);
    bool bArrayBisSorted = Global_isSort(Array_B, Array_B_Length);
    if(bArrayAisSorted && bArrayBisSorted) {
        /*
        * i,j are the index of the Array_A and the Array_B
        */
        int i = 0; 
        int j = 0;

        int *pStoreMergeArrayData = new int[Array_A_Length + Array_B_Length];
        int  MergeArrayIndex = 0;
        while(i < Array_A_Length && j < Array_B_Length) {
            if(Array_A[i] < Array_B[j]) {
                pStoreMergeArrayData[MergeArrayIndex++] = Array_A[i++];
            } else {
                pStoreMergeArrayData[MergeArrayIndex++] = Array_B[j++];
            }
        }

        while(i < Array_A_Length) {
            pStoreMergeArrayData[MergeArrayIndex++] = Array_A[i++];
        }

        while(j < Array_B_Length) {
            pStoreMergeArrayData[MergeArrayIndex++] = Array_B[j++];
        }
        return pStoreMergeArrayData;
    } else {
        std::cout<<"merge failed"<<std::endl;
        exit(1);
    }
    return NULL;
}

int main() {
    int a[] = {1, 2, 3, 5, 8};
    int b[] = {2, 6, 7, 10, 25, 33, 50};
    int *MergeArray = (int *)Global_Merge(a, 5, b, 6);
    Global_printElements(MergeArray, 5+6);
    if(MergeArray != NULL) {
        delete MergeArray;
        MergeArray = NULL;
    }
    return 0;
}



总结:链表也可以采用类似的方法进行合并

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值