x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 2901

# Finding Largest Numbers in Array

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
q_bic
1 Solution

Commented:
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

Commented:
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 Commented:
Thanx for this great idea!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.