Data Structure: Recursion

 1 #include <stdio.h>
2 // Q1.Write a recursive function that
3 // merges two sorted arrays into another array
4 void Merge(int a[], int n1, int b[], int n2, int c[])
5 {
6 if(n1 != 0 && n2 != 0)
7 {
8 if (a[n1-1] < b[n2-1])
9 {
10 c[n1 + n2 -1] = b[n2-1];
11 Merge(a, n1, b, n2-1, c);
12 } // end if
13 else
14 {
15 c[n1 + n2 -1] = a[n1-1];
16 Merge(a, n1-1, b, n2, c);
17 } // end else
18 } // end if
19 else if(n1 == 0 && n2 != 0)
20 {
21 c[n1 + n2 -1] = b[n2-1];
22 Merge(a, n1, b, n2-1, c);
23 } // end else if
24 else if( n2 == 0 && n1 != 0 )
25 {
26 c[n1 + n2 -1] = a[n1-1];
27 Merge(a, n1-1, b, n2, c);
28 } // end else if
29 // n1 = n2 = 0, end function
30 else
31 {
32 return;
33 } // end else
34 }
35
36 // Q2.
37 int FindBiggest(int a[], int N)
38 {
39 if(N == 0)
40 {
41 return a[N];
42 }
43
44 return ( a[N] > FindBiggest(a, N-1))? a[N] : FindBiggest(a, N-1);
45 }
46
47 void main()
48 {
49 int i =0;
50 int ar[5] = { 1,5,9,15,23};
51 int br[4] = { 4,8,22,40};
52 int cr[9];
53 printf("biggest = %d\n\n",FindBiggest(ar, 5));
54
55 Merge(ar, 5, br, 4, cr);
56
57 for(i = 0; i<9; i++)
58 {
59 printf("%d\n",cr[i]);
60 }
61
62 }

  

posted @ 2011-07-23 08:52  Mayus  阅读(150)  评论(0)    收藏  举报