Max-Min Problem (Divide and Conquer Technique) - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Max-Min Problem (Divide and Conquer Technique)

Share This
MaxMin is a recursive algorithm to find the largest and smallest elements from a set of elements.

Let us consider an array of n numbers {a[0], a[1],...,a[n-1]}. Hence, at the time of finding the largest and the smallest element of the array, the largest and the smallest elements are kept in max and min variables respectively.
Max-Min Implementation in C language
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
#include <stdio.h>
int largest, smallest;
void maxmin(int *arr, int i, int j) {
int large, small, mid;
if (i == j) {
largest = smallest = arr[i];
} else {
if (i == j - 1) {
if (arr[i] < arr[j]) {
largest = arr[j];
smallest = arr[i];
} else {
largest = arr[i];
smallest = arr[j];
}
} else {
mid = (i + j) / 2;
maxmin(arr, i, mid);
large = largest;
small = smallest;
maxmin(arr, mid + 1, j);
if (largest < large)
largest = large;
if (smallest > small)
smallest = small;
}
}
}
int main() {
int i, num;
int *arr;
printf("\nMax & Min\n");
printf("\nEnter the total number of elements : ");
scanf("%d", &num);
arr = (int *)malloc(num * sizeof(int));
printf("Enter the elements : \n");
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}
largest = arr[0];
smallest = arr[0];
maxmin(arr, 0, num - 1);
printf("Maximum element is : %d\n", largest);
printf("Minimum element is : %d\n", smallest);
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.