In: Computer Science
Here are the solution to above problem:
/**
* The Class SecondSmallest.
*/
class FindSmallest {
/**
* Prints the smallest.
*
* @param arr the arr
*/
static void printSmallest(int arr[]) {
int first = arr.length;
int second = arr.length;
int arraySize =
arr.length;
if (arraySize < 2)
{
System.out.println("Invalid");
return;
}
first = second =
Integer.MAX_VALUE;
for (int i = 0; i < arraySize;
i++) {
if (arr[i] <
first) {
second = first;
first = arr[i];
} else if
(arr[i] < second && arr[i] != first) {
second = arr[i];
}
}
if (second ==
Integer.MAX_VALUE)
System.out.println("There is no second" + "smallest
element");
else
System.out.println("The smallest element is " + first + " and
second Smallest" + " element is " + second);
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
int arr[] = { 5, 6, 7, 3, 2, 1
};
printSmallest(arr);
}
}
it will be O(n).