Good afternoon friends.
Today's Question.
Write a program in Java to find the second largest element from an array without sorting.
Its not a challenge ✔✔
Solve it.
All the best.
Spammers stay away.
Share
Good afternoon friends.
Today's Question.
Write a program in Java to find the second largest element from an array without sorting.
Its not a challenge ✔✔
Solve it.
All the best.
Spammers stay away.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number. Let's see the full example to find the second largest number in java array.
public class SecondLargestInArrayExample{
public static int getSecondLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}
Output:
Second Largest: 5
Second Largest: 77
public class SecondLargest {
static void printSecondLargest(int[ ] x) {
int first = x[0],
second = x[x.length - 1];
for (int i = 0; i < x.length; i++) {
if (first < x[i]) {
second = first;
first = x[i];
} else if (x[i] > second && x[i] != first)
second = x[i];
}
System.out.println((second = = first) ? "There is no second largest element" : "The Second largest element in the array is - " + second);
}
public static void main(String[ ] args) {
printSecondLargest(new int[ ] {12, 13, 14, 15, 17, 11});
printSecondLargest(new int[ ] {12, 12, 12, 12});
}
}