最近在纸上写一个已排序数组的合并时,花了超过预期的时间。仔细想想,这种要放到毕业找工作那会两下就出来了,原因还在于工作后对基础没有重视,疏于练习。
说开一点,现在搜索引擎的发达确实给问题的解决带来了便利,但是久而久之,对很多东西的掌握其实并不深入。比如淘宝系的人经常分享一些linux内核IO优化相关的内容,咋看一下,原来是这样,觉得也不难嘛,其实不然,如果给一张白纸让你自己把流程画出来,讲解清楚,还有有难度的。这里问题的关键在于很多时候我们只是通过互联网的便利了解某个东西,实际上并不掌握它。
纸上得来终觉浅,绝知此事要躬行。古人早就把道理告诉了我们,只是知易行难而已。
现在IT界新语言、新概念层出不穷,我也很喜欢玩这些新的东西并乐在其中,不过基础始终很重要。
回到正题,以后尽量养成动手的习惯,不管东西大小,内容高深与否,都自己实际过一遍,在博客里记录下来。
问题:将两个已排序数组合并成一个排序数组
这里先不考虑大数据量的情况(在数据量很大时不知大家有什么好的思路或方法?),只做简单数组的处理。
简单代码如下:
说明:之所以把merge函数定义成返回数组长度,是因为后续会有重复数据合并功能的merge版本,考虑到接口一致性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 |
#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; } |
原文:http://www.cnblogs.com/bugchecker/p/3598675.html