Solved

Finding Largest Numbers in Array

Posted on 2002-03-29
3
2,884 Views
Last Modified: 2007-12-19
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
Comment
Question by:q_bic
3 Comments
 
LVL 18

Accepted Solution

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

by:m_onkey_boy
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

by:q_bic
ID: 6917489
Thanx for this great idea!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now