-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax and min from array using Divide and Conquer.c
More file actions
62 lines (49 loc) · 1.46 KB
/
max and min from array using Divide and Conquer.c
File metadata and controls
62 lines (49 loc) · 1.46 KB
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
57
58
59
60
61
62
#include <stdio.h>
// Structure to store both min and max values
struct MinMax {
int min;
int max;
};
// Function to find min and max using divide and conquer
struct MinMax findMinMax(int arr[], int low, int high) {
struct MinMax result, left, right;
// If there is only one element
if (low == high) {
result.min = arr[low];
result.max = arr[low];
return result;
}
// If there are two elements
if (high == low + 1) {
if (arr[low] < arr[high]) {
result.min = arr[low];
result.max = arr[high];
} else {
result.min = arr[high];
result.max = arr[low];
}
return result;
}
// Divide the array into two halves
int mid = (low + high) / 2;
left = findMinMax(arr, low, mid);
right = findMinMax(arr, mid + 1, high);
// Combine results
result.min = (left.min < right.min) ? left.min : right.min;
result.max = (left.max > right.max) ? left.max : right.max;
return result;
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
struct MinMax result = findMinMax(arr, 0, n - 1);
printf("Minimum element: %d\n", result.min);
printf("Maximum element: %d\n", result.max);
return 0;
}