程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> c說話歸並兩個已排序數組的示例(c說話數組排序)

c說話歸並兩個已排序數組的示例(c說話數組排序)

編輯:關於C++

c說話歸並兩個已排序數組的示例(c說話數組排序)。本站提示廣大學習愛好者:(c說話歸並兩個已排序數組的示例(c說話數組排序))文章只能為提供參考,不一定能成為您想要的結果。以下是c說話歸並兩個已排序數組的示例(c說話數組排序)正文


成績:將兩個已排序數組歸並成一個排序數組

這裡先不斟酌年夜數據量的情形(在數據量很年夜時不知年夜家有甚麼好的思緒或辦法?),只做簡略數組的處置。

簡略代碼以下:

解釋:之所以把merge函數界說成前往數組長度,是由於後續會有反復數據歸並功效的merge版本,斟酌到接口分歧性。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int merge(int* ar1, int len1, int* ar2, int len2, int** rtn)
/*++
 DeScription:
    This routine merge two sorted arrays into one sorted array,
    the same values in different arrays will be keeped.

Arguments:
    ar1 - The first sorted array to be merged
    len1 - The num of items in ar1
    ar2 - The second sorted array to be merged
    len2 - The num of items in ar2
    rtn - The caller proviced pointer to get the result array,
        memory allocated for rtn should be free by the caller.

Return Value:
    The num of items in the merge array
--*/
{
    int i=0,j=0,k=0;
    int m=0;
    int* res = NULL;

    if (ar1 == NULL || ar2 == NULL || rtn == NULL) {
        return 0;
    }

    *rtn = (int *)malloc((len1+len2)*sizeof(int));
    if(*rtn == NULL) {
        return 0;
    }
    memset(*rtn, 0, (len1+len2)*sizeof(int));
    res = (int*)*rtn;

    while(i<len1 && j<len2) {
        if (ar1[i]<=ar2[j]) {
            res[k++] = ar1[i++];
        } else {
            res[k++] = ar2[j++];
        }
    }

    while(i<len1) {
        res[k++] = ar1[i++];
    }
    while(j<len2) {
        res[k++] = ar2[j++];
    }

    return  len1+len2;
}

int merge_test()
{
    int a1[] = {0,1,2,5,8,19,34,43,52};
    int a2[] = {1,4,5,12,17,33,42,51,53,65,76};
    int len1 = sizeof(a1)/sizeof(int);
    int len2 = sizeof(a2)/sizeof(int);
    int i = 0, len = 0;
    int* a3 = NULL;
    int* ptr = NULL;

    len = merge(a1, len1, a2, len2, &a3);
    if (a3 == NULL) {
        printf("a3==NULL\n");
        return 1;
    }

    ptr = a3;
    while(i<len) {
        printf("a3[%3d]---->%8d\n", i++, *ptr++);   
    }

    if (a3 != NULL) {
        free(a3);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    merge_test();

    return 0;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved