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
#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;
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.