• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to find 2nd largest array if array values like{10,20,92,81,92,34}  RSS feed

 
anjim anjaiah
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to find 2nd largest array if array values like{10,20,92,81,92,34}
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose that array was sorted. Do you know how to determine the second largest element (assuming that's what you
asked) in that case?

If so, see if you can sort the array in some way.

Greetings,
Piet
 
anjim anjaiah
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ,please exaplain the following progrmam how to sort

package com.usr.arrays;

public class SecondLargestNumberInArray {
public static void main(String[] args) {
int arr[] = { 1, 23, 92, 81, 92, 88};//, 52, 48, 56, 66, 65, 76, 71, 85, 49, 53, 56, 61, 65, 84 };
secondLargeNumber(arr);
}

public static void secondLargeNumber(int[] arr) {
int largest = arr[0];
int secondLargest = arr[0];
System.out.println(arr.length);
System.out.println(largest);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];

} else if (arr[i] > secondLargest&secondLargest!=largest) {
secondLargest = arr[i];

}
/*if(arr[i]<largest){
secondLargest = largest;
largest = arr[i];

} else if (arr[i] > secondLargest) {
secondLargest = arr[i];

}*///For 1st Largest Number

}
System.out.println("second largest in array is:" + secondLargest);

}
}
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please use codetags! (copy the code into the reply area, select the code
and click the "code" button). That will make your code much more easy to read.

Well, At first glance your method

seems to do exactly what you are asking for. No need to sort the array.
Just the line:

you should have a double '&' instead of a single one.

If you do want to sort the array, have a look at the API of the Arrays class.
http://docs.oracle.com/javase/7/docs/api/

Greetings,
Piet
 
anjim anjaiah
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks piet
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!