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

来源:互联网 发布:mac和芭比布朗区别 编辑:程序博客网 时间:2024/05/16 07:17

描述:

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

#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;}



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

原创粉丝点击