开始学习《算法导论》
插入排序(含up/down两种)和N进制数-数组相加
////////////////////insert sort///////////////////////////////
1 #include <stdio.h>
2 #define MAX_LEN 1000
3
4 int* rand_array_generator()
5 {
6 static int local_array[MAX_LEN+1];
7 int i;
8 for (i=0; i<MAX_LEN; ++i) {
9 local_array[i] = ((int)rand()) % 1000;
10 }
11 local_array[i] = 0;
12 return local_array;
13 }
14
15 void insert_array_up(int* arr, size_t arr_size)
16 {
17 static int key = 0;
18 int i=1;
19 int j;
20 for (;i<arr_size; ++i) {
21 key = arr[i];
22 j = i-1;
23 while (j>=0 && arr[j] > key) {
24 arr[j+1] = arr[j];
25 --j;
26 }
27 arr[j+1] = key;
28 }
29 }
30
31 void insert_array_down(int* arr, size_t arr_size)
32 {
33 static int key = 0;
34 int i = 1;
35 int j;
36 for (; i<arr_size; ++i) {
37 key = arr[i];
38 j = i-1;
39 while (j>=0 && arr[j] < key) {
40 arr[j+1] = arr[j];
41 --j;
42 }
43 arr[j+1] = key;
44 }
45 }
46
47 void print_arr(int* arr, size_t size)
48 {
49 int i;
50 printf("%d\n",size);
51 for (i=0; i<size; ++i) {
52 if (i % 15 == 0) {
53 printf("\n");
54 }
55 printf("%4d ", *arr++);
56 }
57 }
58
59 int main(int argc, char* argv[])
60 {
61 int* test_arr;
62 test_arr = rand_array_generator();
63 print_arr(test_arr, MAX_LEN);
64 insert_array_up(test_arr, MAX_LEN);
65 printf("\nThe array after insert up sort:\n");
66 print_arr(test_arr, MAX_LEN);
67 printf("\nThe array after insert down sort:\n");
68 insert_array_down(test_arr, MAX_LEN);
69 print_arr(test_arr, MAX_LEN);
70 return 0;
71 }
/////////////////////////////n-bits number addition////////////////////////////////////////////
1 #include <stdio.h>
2 #define BIN 2
3 #define OCX 8
4 #define DEC 10
5 #define HEX 16
6 #define BITS 100
7
8 int *add_nbits_binary(int* arr_A, int* arr_B, int* arr_C, size_t n)
9 {
10 int i = 0;
11 int carry = 0;
12 int tmp = 0;
13 for (; i<n; ++i) {
14 tmp = arr_A[i] + arr_B[i] + carry;
15 if (tmp > (BIN-1)) {
16 tmp %= BIN;
17 carry = 1;
18 } else {
19 carry = 0;
20 }
21 arr_C[i] = tmp;
22 }
23 arr[i] = carry;
24 }
25
26 int main(int argc, char* argv[])
27 {
28 int arr_A[BITS], arr_B[BITS], arr_C[BITS+1];
29 // initialize the array in different form
30 // bin2, ocx8, dec10, hex16
31 add_nbits_binary(arr_A, arr_B, arr_C, BITS);
32 return 0;
33 }
34