Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum in a array with divide and conquer

Premise that this is homework, and I don't know why I can't use the tag 'homework', so I'll write it down here for clarity.

I have to write a method "int maximum(int[] a, int l, int r)" that finds the maximum in the array A spanning from 'l' to 'r' using a Divide and Conquer approach. Base Case will be when A has a single element inside, so if A.length == 1, return the element. The recursive part should divide the array in two subarrays spanning from A[l] to A[mid], and from A[mid+1] to A[r]. In theory I'm ok with that, but I keep getting a StackOverflowError and I don't understand why.

public class Maximum {
public static void main(String[] args) {
    int[] A = {0, 5, 281, 3, 9, 4, 88, 16, 17, 60};
    int l = 0;
    int r = A.length-1;
    System.out.println("Maximum of the array: "+maxArray(A, l, r));
}
public static int maxArray(int[] A, int l, int r) {

    //Assuming that the index of array is '0' and not '1', l is 0. Else, put 1.

    if (A.length == 1) {
        return A[l];
    }

    int mid = r/2;
    int maxLeft = 0;
    int maxRight = 0;

    maxLeft = maxArray(A, l, mid);        //Here is the StackOverflowError!
    maxRight = maxArray(A, mid+1, r);

    if (maxLeft < maxRight) {
        return maxRight;
    } else 
return maxLeft;
}
}
like image 322
Monok Avatar asked Dec 15 '22 05:12

Monok


2 Answers

You have a problem in the calculation of mid.

It should be

int mid = (l+r)/2;

Beside that,

if (A.length == 1) {
    return A[l];
}

should be

if (l == r) {
    return A[l];
}

since you are always passing the original array to your method, so A.length can only be 1 if the original array has a single element.

like image 56
Eran Avatar answered Dec 17 '22 00:12

Eran


In Divide and Conquer approach when we calculating index of mid element, that mean is sum of first and last index divide by 2.

Also, when left element index is same as right element index then it means array has one element and then only we return that single array element.

your solution is :

 public class Helloworld{

 public static void main(String []args){
  int[] A = {0, 5, 281, 3, 9, 4, 88, 16, 17, 60};
int l = 0;
int r = A.length-1;
System.out.println("Maximum of the array: "+maxArray(A, l, r));
 }

 public static int maxArray(int[] A, int l, int r) {

//Assuming that the index of array is '0' and not '1', l is 0. Else, put 1.

if (l == r) { // checking codition/
    return A[l]; 
}

int mid = (l+r)/2; // Calculating mid.
int maxLeft = 0;
int maxRight = 0;

maxLeft = maxArray(A, l, mid);        
maxRight = maxArray(A, mid+1, r);

if (maxLeft < maxRight) {
    return maxRight;
} else return maxLeft;
}}
like image 38
UDID Avatar answered Dec 17 '22 02:12

UDID