Da Assignment 1
Da Assignment 1
Experiment
1(DivideandConquer)
Aim: Implementationofmin-max algorithmusingdivideandconquer.
Theory:
Max-Min problem is to find a maximum and minimum element from the given array. We
caneffectivelysolveit usingdivideand conquerapproach.
In the traditional approach, the maximum and minimum element can be found by
comparingeachelementandupdatingMaxandMinvaluesasandwhenrequired.Thisapproachissim
plebutitdoes(n–1)comparisonsforfindingmaxandthesamenumberofcomparisonsforfindingthe
min. It results in a total of 2(n – 1) comparisons. Using a divide and conquer approach,
wecanreducethe number of comparisons.
Divideandconquer approachforMax.Minproblem worksin threestages.
Algorithm:
AlgorithmDC_MAXMIN(A,low,high)
// Description : Find minimum and maximum element from array using divide and
conquerapproach
//Input :ArrayAoflength n,and indiceslow =0and high=n-1
//Output: (min,max)variables holdingminimum andmaximum elementofarray
Complexity:
Timecomplexity:O(n)
Example:
LabAssignment:
1. Write a program to find the minimum and maximum of the following array using
divideandconquerapproach.50, 40, -5, -9, 45, 90, 65, 25, 75
#include <stdio.h>
void find_min_max(int arr[], int low, int high, int *min, int *max) {
if (low == high) { // Base case: Only one element in the array
*min = *max = arr[low];
DepartmentofInformation Technology
} else if (high - low == 1) { // Base case: Only two elements in the array
if (arr[low] < arr[high]) {
*min = arr[low];
*max = arr[high];
} else {
*min = arr[high];
*max = arr[low];
}
} else {
int mid = (low + high) / 2;
int min1, max1, min2, max2;
// Divide the array into two parts and recursively find min/max in each part
find_min_max(arr, low, mid, &min1, &max1);
find_min_max(arr, mid + 1, high, &min2, &max2);
int main() {
int arr[] = {50, 40, -5, -9, 45, 90, 65, 25, 75};
int size = sizeof(arr) / sizeof(arr[0]);
int min_val, max_val;