Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Returning the smallest element of the given non-empty array

Tags:

java

I am studying Java and trying to find the bug in my code.

It is suppose to return the smallest element of the given non-empty array.

It works with B = [-3, 4, -2, -2]

Can you tell me what I am doing wrong here?

class Test {
    int test(int[] B, int[] C) {
        int ans = 0;
        for (int i = 1; i < B.length; i++) {
            if (ans > B[I]) {
                ans = B[i];
            }
        }
        return ans;
    }
}

1 Answers

The cause of your bug is because you're setting the ans variable to 0, instead of setting it to the maximum integer value ( MAX_VALUE ) as indicated by most solutions above :

int test(int[] B) {
    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < B.length; i++) {
        if (ans > B[I]) {
            ans = B[i];
        }
    }
    return ans;
}

Your solution will only work if the given array consists of at-least 1 non-positive element. Once you have an Array with all positive elements, you solution will always return a 0 because no element in an array will ever be less than your initially assumed minimum which is zero in your case.

Alternatively to using streams : you can sort the Array first and get the first element, assuming it will be sorted in ascending order:

int test(int[] B) {
    Arrays.sort(B); // Sorts the array in ascending order
    return B[0];
}
like image 93
Sllie Dube Avatar answered Jun 24 '26 13:06

Sllie Dube