Solved

# Finding Largest Numbers in Array

Posted on 2002-03-29
2,884 Views
Hi, How do write a function that returns the largest number in an array on the first execution of the loop, then on the second execution, it returns the second largest, then the third and so on till finally the smallest number.

Thanx!!
0
Question by:q_bic

LVL 18

Accepted Solution

bobbit31 earned 25 total points
ID: 6905431
try this (doesn't support negative numbers):

int prevLargest=0;
int curLargest=0;
int[] yourArray = { 5,2,3,4,0,121,157,54,33,18,76,32,12,87,43,343,68 };

for (int i=0;i<yourArray.length;i++) {
for (int j=0;j<yourArray.length;j++) {
if (i==0) {
if (yourArray[j]>curLargest) { curLargest = yourArray[j]; }
} else {
if (yourArray[j]>curLargest && prevLargest>yourArray[j]) { curLargest = yourArray[j];}
}
}

out.println("Largest = " + curLargest);
prevLargest = curLargest;
curLargest = 0;

}
0

LVL 4

Expert Comment

ID: 6905618
Or...

int[] array = {3,4,8,1,4,2,9,10,2,5,45,4};

Arrays.sort(array);

now, you array will be sorted, so you only have to loop over it once.

If you need to keep the order of the first array, allocate a second array and do System.arrayCopy before the sort.
0

Author Comment

ID: 6917489
Thanx for this great idea!!
0

## Featured Post

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…