Daa 1 (Mergesort)
Daa 1 (Mergesort)
PROBLEM STATEMENT
Write a program in C to find out maximum and minimum elements in an array using divide
and conquer approach.
ALGORITHM
1. Input: An array `ARR` of size `N`, and two indices `LOW` and ` HIGH ` representing the
current segment of the array.
2. Base Cases:
- IF `LOW == HIGH`:
- This means there is only one element in the current segment.
- Set `max = ARR [LOW]` and `min = ARR [LOW]`.
- Return the result.
- If ` HIGH == LOW + 1`:
- This means there are two elements in the current segment.
- Compare ` ARR [LOW]` and ` ARR [HIGH]`:
- If ` ARR [LOW] > ARR [HIGH]`, set `max = ARR [LOW]` and `min = ARR [HIGH]`.
- Otherwise, set `max = ARR [HIGH]` and `min = ARR [LOW]`.
- Return the result.
3. Recursive Case:
- Calculate the midpoint: `mid = (LOW + HIGH) / 2`.
- Recursively find the maximum and minimum in the left half of the array:
- Call `findMinMax(ARR, LOW, mid)` and store the result in `leftResult`.
- Recursively find the maximum and minimum in the right half of the array:
- Call `findMinMax(ARR, mid + 1, HIGH)` and store the result in `rightResult`.
4. Combine Results:
- Set `result.max` to the maximum of `leftResult.max` and `rightResult.max`.
- Set `result.min` to the minimum of `leftResult.min` and `rightResult.min`.
5. Output: Return the combined result containing the maximum and minimum values.
CODE
#include <stdio.h>
#include <limits.h>
typedef struct {
int max;
int min;
} MinMax;
return result;
}
int main() {
int arr[] = {20, 2, 40, 4, 50};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
OUTPUT
COMPLEXITY ANALYSIS
- Time Complexity: The time complexity of this algorithm is (O(n)) because each element is
compared a constant number of times.
- Space Complexity: The space complexity is (O(log n)) due to the recursive call stack in the
worst case.