-1
int[] smallest = {4,5,1,3,7};
System.out.println(getMinimum(smallest));

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

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

    }
    return min;
}

This (above) works but this (below) doesn't:

int[] smallest = {4,5,1,3,7};
System.out.println(getMinimum(smallest));

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

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

    }
    return min;
}

I can't figure out why, in the top example getMinimum returns 1, but in the bottom example getMinimum returns 3? Both are doing the same thing yet one is wrong and the other right? Is it because I assigned min to equal 0?

Branden
  • 17
  • 3

4 Answers4

2

In your second example you're always comparing against a[0], not against whatever your current minimum value is. As a result, the answer you get will always be the last number in the array that is smaller than the value in a[0] which in your case is 3

If your intention was to sort the array, as the title of your question implies, then you probably meant to put the minimum value into a[0] each time it was updated. This wouldn't actually sort the array correctly but it would put you on the right track and fix the comparison problem

rdowell
  • 729
  • 4
  • 15
1

The immediate problem of your second version is nicely solved in the answer by rdowell.

However, after fixing it by comparing to min instead to always a[0] you will have a second problem.

If you init min with 0 it is not possible to find a lower value, at least not among the positive values of your example.
Initialising it with a[0] uses a possible value and the others can be lower.
If you do not want to init with first element, then init higher than any value can be. For the single-digit example "10" would be a good value, then already the first value is lower and the others have a chance, too.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

In the second example, change

if(a[i] < a[0])

to

if(a[i] < min)

That is the discernment. Doesn't have anything to do with you setting min to 0 or a[0]. Especially since in the second example you don't even compare a[i] to min.

kay
  • 356
  • 1
  • 4
  • 18
0

You are always comparing the first value in the Array when you should be comparing to the previous smallest value. The second example never calculates a minimum since min is set to 0 and unless the Array contains negative values, min will stay as 0. The following code should work:

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

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

}
return min;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80