- 论坛徽章:
- 0
|
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 void swap(int *a, int *b) {
5 int tmp = *a;
6 *a = *b;
7 *b = tmp;
8 }
9
10 int sum(int arr[], int len) {
11 int tmpSum = 0;
12 int i = 0;
13 for (; i < len; i++) {
14 tmpSum += arr[i];
15 }
16 return tmpSum;
17 }
18
19 int comp(const void *p, const void *q) {
20 return (*(int*)p - *(int*)q);
21 }
22
23 int main(int argc, char *argv[]) {
24 int arr[] = {10, 45, 69, 78, 36};
25 int brr[] = {25, 85, 71, 63, 42};
26
27 int asum = 0;
28 int bsum = 0;
29 int tmpSum = 0;
30 int len = 5;
31 int i = 0;
32
33 qsort(arr, len, sizeof(int), comp);
34 qsort(brr, len, sizeof(int), comp);
35
36 asum = sum(arr, len);
37 bsum = sum(brr, len);
38 tmpSum = abs(asum - bsum);
39 printf("asum = %d, bsum = %d, tmpSum = %d\n", asum, bsum, tmpSum);
40
41 for (i = len -1; i >= 0; i--) {
42 swap(&arr[i], &brr[i]);
43 asum = sum(arr, len);
44 bsum = sum(brr, len);
45
46 if (tmpSum > abs(asum - bsum)) {
47 tmpSum = abs(asum - bsum);
48 } else {
49 swap(&arr[i], &brr[i]);
50 }
51 printf("asum = %d, bsum = %d, tmpSum = %d\n", asum, bsum, tmpSum);
52 }
53
54 return 0;
56 } |
|