兩個已排序數組的合並-C語言


最近在紙上寫一個已排序數組的合並時,花了超過預期的時間。仔細想想,這種要放到畢業找工作那會兩下就出來了,原因還在於工作后對基礎沒有重視,疏於練習。

說開一點,現在搜索引擎的發達確實給問題的解決帶來了便利,但是久而久之,對很多東西的掌握其實並不深入。比如淘寶系的人經常分享一些linux內核IO優化相關的內容,咋看一下,原來是這樣,覺得也不難嘛,其實不然,如果給一張白紙讓你自己把流程畫出來,講解清楚,還有有難度的。這里問題的關鍵在於很多時候我們只是通過互聯網的便利了解某個東西,實際上並不掌握它。

紙上得來終覺淺,絕知此事要躬行。古人早就把道理告訴了我們,只是知易行難而已。

現在IT界新語言、新概念層出不窮,我也很喜歡玩這些新的東西並樂在其中,不過基礎始終很重要。

回到正題,以后盡量養成動手的習慣,不管東西大小,內容高深與否,都自己實際過一遍,在博客里記錄下來。

 

問題:將兩個已排序數組合並成一個排序數組

這里先不考慮大數據量的情況(在數據量很大時不知大家有什么好的思路或方法?),只做簡單數組的處理。

簡單代碼如下:

說明:之所以把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;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM