public static int min(int[] list)
{
if(list == null || list.length < 1)
throw new IDTenTException();
int min = list[0];
for (int c = 1; c < list.length; c++)
min = min(min, list[c]);
return min;
}
public static int min(int a, int b)
{
if (a > b)
return b;
return a;
}
Here's some functions if Java to determine the lowest integer in an array or integers. It runs in O(n) time and if you throw them into a class, you can call them without having to create an instance of the class. Though if you do throw this into a class, you'll have to either change the type of exception thrown or define an exception called IDTenTException, since I just made that up.
We can guarantee these function's validity because every element in the array is checked (note the indices of each element rang from 0 to the length -1, not 1 to length) against the current min value. We also throw the exception in case someone wasn't smart enough to give us a usable array.
2 comments:
I can see your intent, but this is not right.
For one, you use the function min(a, list), but you do not define it. You only define the base case of this, when is list is just one element, min(a,b).
Maybe this is how you wanted to write:
m = a_large_number;
min(m, list) =
let a be the first element of the list,
i.e., list = a::rest_of_the_list;
if (rest_of_the_list == NULL)
return min(m, a);
else
m = min(m, a);
return min(m, rest_of_the_list);
Does this make sense?
Umm... You might want to take a second look at my code. I am not trying to use recursion. I am, in fact, using polymorphism. I defined two different min methods which are differentiated by the arguments they accept.
The min(int a, int b) method simply returns which ever is smallest between a and b, making it equivalent to the Math.Min method that is part of the Java library.
The min(int[] list) method iterates through the elements of the list and uses the min(int a, int b) method to compare them. That is all.
I'm sorry if it was confusing.
Post a Comment