#include <stdio.h>
typedef struct{
int max;
int min;
} result;
result maxmin(int a[], int low, int high){
result res;
int i;
if(low == high){
res.max = a[low];
res.min = a[low];
} else if (low + 1 == high){
if(a[low] < a[high]){
res.max = a[high];
res.min = a[low];
} else {
res.max = a[low];
res.min = a[high];
}
} else {
int mid = (low + high) / 2;
result res1, res2;
res1 = maxmin(a, low, mid);
res2 = maxmin(a, mid + 1, high);
if(res1.max > res2.max)
res.max = res1.max;
else
res.max = res2.max;
if(res1.min < res2.min)
res.min = res1.min;
else
res.min = res2.min;
}
for(i = low; i <= high; i++)
printf("%d ", a[i]);
printf("\nmin=%d max=%d\n", res.min, res.max);
return res;
}
int main(){
int a[] = {22, 13, -5, -8, 15, 60, 17, 31, 47};
int n = sizeof(a) / sizeof(int);
result res = maxmin(a, 0, n - 1);
printf("%d %d", res.min, res.max);
return 0;
}
Output:
22 13
min=13 max=22
-5
min=-5 max=-5
22 13 -5
min=-5 max=22
-8 15
min=-8 max=15
22 13 -5 -8 15
min=-8 max=22
60 17
min=17 max=60
31 47
min=31 max=47
60 17 31 47
min=17 max=60
22 13 -5 -8 15 60 17 31 47
min=-8 max=60
-8 60
Хахаха заавал ингэж элий олдог нь ямар учиртай юм бэ :)
ReplyDeleteDivide and Conquer-г энгийн жишээгээр л харуулж байгаа ухаантай шиг.
Delete