Thread: Find the second largest number in the array

1. Member
Join Date
Jan 2011
Posts
30
Rep Power
0

Find the second largest number in the array

I have written the following code for finding the 1st largest number in the given array and please do correct me in case there is some error in the program and can any one help me in finding the 2nd largest number in the array.
The code which i have written is as follows:

public class Assignment1 {

public static void main(String args[]) {
int i;
int temp = 95;

int arr[] = {95, 20, 34, 100, 9,150};
for (i = 0; i < arr.length - 1; i++) {

if (i == 0) {
temp = arr[i];
} else if (temp < arr[i]) {

temp = arr[i];

}
}
System.out.println("Largest is :" + temp);

}
}

2. Senior Member
Join Date
Dec 2010
Posts
100
Rep Power
0
Hi - have you tested your code? If so, and if it works correctly, you can do a second pass through the array to find the second largest number, using some if statements like you have done.

Also, are you not allowed to sort the array?

Best,

3. Senior Member
Join Date
Dec 2010
Posts
100
Rep Power
0
Hi - also, looks like you are missing the last element in your loop, due to the condition arr.length - 1. I would suggest changing the for loop to :
Java Code:
`for(int i = 0; i < arr.length; i++)`
Secondly, why are you initializing temp to 95? I would initialize it to the lowest possible int value:
Java Code:
`int temp = Integer.MIN_VALUE;`
and get rid of the first if statement you have as it would just be a waste checking if i==0 each time the loop runs.

best,

4. Member
Join Date
Jan 2011
Posts
30
Rep Power
0
My code works .I am not able to write the code to find the second highest number.Any help or suggestions

I have written the following code for finding the 1st largest number in the given array and please do correct me in case there is some error in the program and can any one help me in finding the 2nd largest number in the array.
One loop and a couple of if-statements can do the job: think of it, suppose you have two numbers: first and second representing the largest and second largest numbers so far; also suppose a current number curr. If curr is larger or equal to first, what to do? Else, if curr is larger or equal to second, what to do?

kind regards,

Jos

6. Member
Join Date
Jan 2011
Posts
30
Rep Power
0

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•