Reputation: 385
Ths is a question from a past paper. I have been asked to create a static method arrayMin
to find the smallest value in the array arr
.
I have to use a while loop and on each iteration, the variable min
will return the smallest number from the first i
elements.
Is there a way to do this without calling another method/for loop and strictly using the while loop, as the question is only worth 4%(including writing loop invariants and javadoc). Not sure if I am overcomplicating the problem.
public class Revision {
public static int arr[] = new int[] { 5, 8, 4, 3, 6, 2 };
public static int min = 1;
public static int arrayMin() {
int i = 0;
if (arr == null) {
return 0;
} else {
while (i < arr.length) {
// some function/method call to find smallest number of arr[i]
i++;
return min;
}
}
return min;
}
public static void main(String[] args) {
System.out.println(arrayMin());
}
}
Upvotes: 1
Views: 24502
Reputation: 609
You can use a index variable to keep in track of the number of positive hits and if the corresponding numbers index value is one lesser the array size, that number is the smallest
class testtt{
static int small=0;
public static void main(String[] args) {
int arr[] = {9,2,3,4,5,6,7,8};
int i,index=0;
for(int q:arr)
{
for(i=0;i<arr.length;i++)
{
if(q<arr[i])
{
small=q;
index++;
}
}
if(index==arr.length-1)
System.out.println(small);
}
}
}
Upvotes: 0
Reputation: 1
multiple ways to do it, but here is one. public static int arrayMin(int[] arr) {
boolean isFirstElement = true;
int smallestNumber= 0;
int index = 0;
while(index < arr.length) {
int temp= arr[index];
index++;
if (isFirstElement) {
smallestNumber = temp;
isFirstElement = false;
} else if (smallestNumber > temp) {
smallestNumber = temp;
}
}
}
Upvotes: 0
Reputation: 91299
A couple of things:
arrayMin
method;min
should be a local arrayMin
variable, not static;min
should be initialized to Integer.MAX_VALUE
. If you initialize it with 1
, and 2
happens to be the min value of the array, you'll never return it;return min
, the method ends. There's probably some confusion over the the variable min will return the smallest number from the first i elements phrase. It probably means that in each iteration, the variable min
will have (not return) the smallest number from the first i
elements.Here's a refactor:
public static int arrayMin(int[] arr) {
int i = 0;
int min = Integer.MAX_VALUE;
if (arr == null) {
return 0; // What if 0 is the minimum value? What do you want to do in this case?
} else {
while (i < arr.length) {
if (arr[i] < min) {
min = arr[i];
}
i++;
}
}
return min;
}
Upvotes: 8
Reputation: 44808
You need to have a variable outside of the loop called min
. You will use the loop to find the minimum of the array, and return min
when the loop is complete.
} else {
int min = Integer.MAX_VALUE;
while(i < arr.length) {
// is arr[i] < min? If so, it's the new minimum
i++;
}
return min;
}
Upvotes: 6