This Java Code will print the Second Smallest number from the specified Array list
import java.util.Scanner;
public class Test {
public static int second (int[] values) {
int min = -1, secondMin = -1;
int firstValue = values[0];
int secondValue = values[1];
if (firstValue < secondValue) {
min = firstValue;
secondMin = secondValue;
} else {
min = secondValue;
secondMin = firstValue;
}
int nextElement = -1;
for (int i = 2; i < values.length; i++) {
nextElement = values[i];
if (nextElement < min) {
secondMin = min;
min = nextElement;
} else if (nextElement < secondMin) {
secondMin = nextElement;
}
}
return secondMin;
}
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("Enter Size of an array: ");
int n = input.nextInt();
int[] valueArray = new int[n] ;
System.out.println ("Enter The array elements: ");
for (int i = 0; i< n; i++) {
valueArray[i] = input.nextInt();
}
System.out.println("Second Sortest element in given array is: " + second(valueArray));
}
}
import java.util.Scanner;
public class Test {
public static int second (int[] values) {
int min = -1, secondMin = -1;
int firstValue = values[0];
int secondValue = values[1];
if (firstValue < secondValue) {
min = firstValue;
secondMin = secondValue;
} else {
min = secondValue;
secondMin = firstValue;
}
int nextElement = -1;
for (int i = 2; i < values.length; i++) {
nextElement = values[i];
if (nextElement < min) {
secondMin = min;
min = nextElement;
} else if (nextElement < secondMin) {
secondMin = nextElement;
}
}
return secondMin;
}
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("Enter Size of an array: ");
int n = input.nextInt();
int[] valueArray = new int[n] ;
System.out.println ("Enter The array elements: ");
for (int i = 0; i< n; i++) {
valueArray[i] = input.nextInt();
}
System.out.println("Second Sortest element in given array is: " + second(valueArray));
}
}
No comments:
Post a Comment