import java.util.Scanner;
public class MinMaxDivideConquer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// Initialize parameters
int i = 0;
int j = n - 1;
int min = arr[0];
int max = arr[0];
// Call the divide and conquer function
findMinMax(arr, i, j, min, max);
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
}
public static void findMinMax(int[] arr, int i, int j, int min, int max) {
if (i == j) {
min = max = arr[i];
} else if (i == j - 1) {
if (arr[i] < arr[j]) {
min = arr[i];
max = arr[j];
} else {
min = arr[j];
max = arr[i];
}
} else {
int mid = (i + j) / 2;
int min1 = 0;
int max1 = 0;
findMinMax(arr, i, mid, min, max);
findMinMax(arr, mid + 1, j, min1, max1);
if (min1 < min) {
min = min1;
}
if (max1 > max) {
max = max1;
}
}
}
}
Using divide and conquer, I should get Max and min of the the array given by user but the first element is coming as Max and min.as the code should be basic and simple I am not using integer.min_value etc..,I couldn't find where the error was after these many trails .
you have called the recursive findMinMax method but it never returned and assigned back. In recursive the previous method data to be processed in the current method data. Next this min1 & max1 which are assigned zero , how about the second findMinMax called with same min max . there the logical mistakes happened. You have said its divide and conquer. In that sense you have divided into two groups lets say right and left form the left you have to find min & max and from the right you have to find min and max from the output of both left and right you have to check which is min and max, thats the last if else condition , there the failure arise in your code.
}