methods interfere with finding the "Min" and "Max" numbers of array

Viewed 53

This is a perceptual question.
I want to know why there is an interference with these two independent methods.
I know both are reading the same array (my_array)
independently every response of the methods is correct. But when I turn on both of them (min and max methods), the response of the below method is wrong.

This is my code:

public class myPractice {
    public static int max(int[] my_array1) {
        int i = 0;
        int max = my_array1[i];
         for(i = 0; i < my_array1.length-1; i++) {
             if(my_array1[i] > my_array1[i+1]) {
                 my_array1[i+1] = my_array1[i];
                 max = my_array1[i];
             }else {
                 max = my_array1[i+1];
             }
         } 
         System.out.println("Max= " +max); 
         return max;
    }
    
    public static int min(int[] my_array2) {
        int j = 0;
         int min = my_array2[j];
         for(j = 0; j < my_array2.length-1; j++) {
             if(my_array2[j] < my_array2[j+1]) {
                 my_array2[j+1] = my_array2[j];
                 min = my_array2[j];
             }else {
                 min = my_array2[j+1];
             }
         } 
         System.out.println("Min= " +min);
         return min;
    }
     public static void main(String args[]) {
         
         int[] my_array = {25, 14, 56, 5, 36, 89, 77, 18, 29, 49};
         
         max(my_array);
         min(my_array);

    }
    
}
1 Answers

The issue is that you are altering the input array in the min and max methods:

my_array1[i+1] = my_array1[i];

As a result, in the next call, you are manipulating an array different from the initial one. As a matter of fact, in your script, max(my_array) sets my_array equals to [25, 25, 56, 56, 56, 89, 89, 89, 89, 89].

You can simplify min and max as the following ones:

public static int max(int[] myArr) {
    int max = myArr[0];

    for (int i = 1; i < myArr.length; i++){
        if (myArr[i] > max)
            max = myArr[i];
    }

   return max;
}

public static int min(int[] myArr) {
    int min = myArr[0];

    for (int i = 1; i < myArr.length; i++){
        if (myArr[i] < min)
            min = myArr[i];
    }

    return min;
}

Furthermore, I want to recommend some best practices:

  • use the camel case when programming in java. Write myArray instead of my_array;
  • print the result of a method in the main:
    public static void main(String[] args) {
    
        int[] myArray = {25, 14, 56, 5, 36, 89, 77, 18, 29, 49};
    
        System.out.println("Max = " + max(myArray));
        System.out.println("Min = " + min(myArray));
    
    }
    
Related