[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2898
  • Last Modified:

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
Asked:
q_bic
1 Solution
 
bobbit31Commented:
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
 
m_onkey_boyCommented:
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
 
q_bicAuthor Commented:
Thanx for this great idea!!
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now