« Given an array {7, 1, 3, 2, 2, 4, 4, 5, 1}, write a program (java) that will match the first duplicate and return | Main | Write a program to do merge sort recursively »

Given an array {7, 5, 8, 3, 1, 4} - write a program that will return the largest 3 nos


public class ReturnThreeMaxNos {

 public static void main(String[] args)
 {
  int array[] = {
    1, 22, 1, 3, 212, 4, 43, 5, 1
  };
  
  int max = -1;
  int max2 = -1;
  int max3 = -1;
  
  for (int i : array) {
   if (i > max) {
    max3  = max2;
    max2 = max;
    max = i;
   }
   else if (i > max2) {
    max3 = max2;
    max2 = i;
   }
   else if (i > max3) {
    max3 = i;
   }
  }
  
  Formatter f = new Formatter();
  f.format("The max is: %d\n The 2nd max is: %d\n the 3rd max is: %d", max, max2, max3);
  System.out.print(f.toString());
  
 }
}

TrackBack

TrackBack URL for this entry:
http://khanna111.com/blog-mt/mt-tb.fcgi/33


Hosting by Yahoo!

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)