+ 1

How to get second highest element in unsorted int[] ? Please someone explain me with Java code :)

18th Feb 2017, 4:36 AM
Sani Suryavanshi
Sani Suryavanshi - avatar
4 Respuestas
+ 4
Why did you mention 'unsorted'? If you want second largest element, sort the array in ascending order and get second last element. /* Sorting in Ascending order */ for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } /* Getting second last element */ arr[arr.length - 2]
18th Feb 2017, 5:13 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 3
@Er. SANI : There's no direct way without sorting. But, you can find the largest number first and then find the largest number in the remaining array.
18th Feb 2017, 5:49 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 1
@krishna i don't want to sort array elements. is there any way to get second highest in unsorted array.
18th Feb 2017, 5:39 AM
Sani Suryavanshi
Sani Suryavanshi - avatar
+ 1
The safest way is to do comparison loop twice if you don't want to sort the array. If you want to do it in a single loop, you will get incorrect result when the first element is the biggest one. int[] array = new int[]{9, 5, 6, 7, 8, 4, 2, 6, 1}; int max1, pos1, max2, pos2; pos1 = -1; max1 = Integer.MIN_VALUE; for (int i=0; i<array.length; i++) { if (array[i] > max1) { // if you uncomment below and make a single loop // you will get incorrect result // pos2 = pos1; // max2 = array[pos2]; pos1 = i; max1 = array[pos1]; } } pos2 = -1; max2 = Integer.MIN_VALUE; for (int i=0; i<array.length; i++) { if (i == pos1) continue; // skip the biggest one if (array[i] > max2) { pos2 = i; max2 = array[pos2]; } } System.out.println("max2 = "+max2);
18th Feb 2017, 5:54 AM
Jian-hua Yeh
Jian-hua Yeh - avatar