To get the minimum value in an array, I made the method minValue
public int minValue() {
int smallestVal = 0; //field
if (intArray.length == 0) { //if array is empty, return 0
return 0;
}
int a = intArray[0]; //field
for (int i : intArray) {
if (i > a) {
smallestVal = a;
}
else {
a = i;
}
}
return smallestVal; //returns the smallest value
}
Tested it in a main method with arr9 = { 1, 2, -1, 40, 1, 40, 0, 0, -3, 2, 2, -2, -5, 0, 1, -4, -5 }
and arr10 = { 4, 5, 5, 4, 1, 5, -3, 4, -1, -2, -2, -2, -2, -2, -2, 1, 4, 5, -5 }
For arr9, it returns -5 but for arr10 it returns -3 instead of -5. Is there something I need to change in my code?
CodePudding user response:
The reason your code doesn't work with the second array is because it will never set smallestVal
when the smallest value is the last location in the array.
There is no need for your variable a
here. Replace it with this:
int smallestVal = intArray[0]; //field
for (int i : intArray){
if (i < smallestVal){
smallestVal = i;
}
}
CodePudding user response:
if (i > a) {
smallestVal = a;
}
else {
a = i;
}
This sets a
to the value of i
if i
is smaller or equal a
and sets smallestVal
to the value of a
if i
is greater than a
. In the case that i
is never greater than a
after a
got updated smalledtVal
will not be updated to the smallest value. I'd suggest getting rid of smallestVal
and just returning a
as a
should always contain the smallest value. That being said a
should probably be named smallestVal
as it's a more descriptive name.