思路:声明变量第一位 第二位,遍历数组,进行首位和第二位的比较和赋值。时间复杂度为N
当然也可以通过排序得到第二位的数据,但是时间复杂度为N2
static void print2Smallest(int arr[]) {
int first, second, arr_size = arr.length;
/* There should be atleast two elements */
if (arr_size < 2) {
System.out.println(" Invalid Input ");
return;
}
first = second = Integer.MAX_VALUE;
for (int i = 0; i < arr_size; 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);
System.out.print("--" + first);
System.out.print("--" + second);
}