Obtener menor valor de un arreglo de enteros
Java
1.359 visualizaciones desde el 11 de Diciembre del 2020
Dado un arreglo de enteros, no vacio, obtener el valor menor contenido en el.
import java.util.Arrays;
public class Main
{
private static int menor(int valores[]) {
if( valores == null || valores.length == 0) {
throw new IllegalArgumentException("Sin datos, no hay menor");
}
int menor = valores[0];
for(int valor: valores) {
if( valor < menor ) {
menor = valor;
}
}
return menor;
}
public static void testMenor(int valores[], int valorEsperado) {
int valorObtenido = menor(valores);
System.out.print( "menor( " + Arrays.toString(valores) + " ) = " + valorObtenido + " ");
if( valorObtenido == valorEsperado ) {
System.out.println("\tOK");
} else {
System.out.println("\tERROR, se esperaba " + valorEsperado );
}
}
public static void main(String[] args) {
testMenor( new int[] { 1, 2, 3, 4 }, 1); // Arreglo creciente
testMenor( new int[] { 4, 3, 2, 1 }, 1); // decreciente
testMenor( new int[] { 2, 1, 4, 3 }, 1); // arriba, abajo
testMenor( new int[] { 4, 4, 4, 4 }, 4); // todos iguales
testMenor( new int[] { 123 }, 123 ); // solo 1 valor
testMenor( new int[] { -4, -3, -2, -1 }, -4); // valores negativos
testMenor( new int[] { -4, 3, -2, 1 }, -4); // valores positivos y negativos
testMenor( new int[] { 200, 100, 400, 300 }, 100); // valores mas grandes
}
}
Comentarios sobre la versión: 1.0 (0)
No hay comentarios