E. Graham
E. Graham

Reputation: 11

Printing the 2 highest numbers in an Array

So I created a method called max2 that is supposed to return the 2 highest values in an array. I am able to return the highest value however I cannot figure out how to return the second highest value.

Here is my code: Main Method

    public static void main(String[] args) {
        Integer intArray[] = { 13, 25, 46, 65, 12, 23};
        Double doubleArray[] = {1.2, 3.4, 1.1, 0.1, 5.6};
        String stringArray[] = {"H", "E", "L", "L", "O"};

    System.out.println("The smallest number is: " + myMin(doubleArray));
    System.out.println("The median is: " + median(doubleArray));
    System.out.println("The median is: " + median(stringArray));
    System.out.println("The max is: " + max2(intArray));
}

My max2 method:

public static <E extends Comparable<E>> E max2(E... elements) {

Arrays.sort(elements);

    E max = elements[0];
    for (E element : elements) {
        if (element.compareTo(max) > 0) {
            max = element;

        }
    }
    return max;

}

I am wondering if there is a way to get the 2nd to last index of the array. Ideally I would want this to work with any array. I am looking to be pointed into the right direction. Thank you for your help.

Upvotes: 1

Views: 527

Answers (3)

Zabuzard
Zabuzard

Reputation: 25903

Your approach

Your current approach doesn't make much sense. You have

Arrays.sort(elements);

E max = elements[0];
for (E element : elements) {
    if (element.compareTo(max) > 0) {
        max = element;
    }
}
return max;

That is, you first sort the array. And then you traverse all elements to find the max-element. First, you wanted to find the second to max element, not the max element. And second, why are you sorting when you then don't exploit the fact that it is sorted, but just iterate through the array?

Let me show you some solutions.


Full sort

Probably the easiest solution is to do a full sort and then access the second to last element (elements are sorted ascending by default):

Arrays.sort(values);
return values[values.length - 2];

There is one problem with this approach. Arrays.sort sorts the given array inline. That is, it changes your input array. You probably do not want this and only want to sort a copy. So:

E[] copyValues = values.clone();
Arrays.sort(copyValues);
return copyValues[copyValues.length - 2];

Partial sort

Instead of doing a full sort, you can always do a partial sort (k-sort). This will be faster, as you only need to sort the array descending for 2 elements. You can do a partial sort using a PriorityQueue. Insert all elements into the queue and then call poll two times. The queue always gives you the next element according to the order.

PriorityQueue<E> queue = new PriorityQueue<>(Comparator.reverseOrder());
queue.addAll(Arrays.asList(values);

queue.poll(); // Greatest element
return queue.poll(); // Second to greatest element

Iteration

Probably the fastest solution is to do one ordinary iteration and remembering the greatest, as well as the second to greatest element. This is similar to the loop in your approach, but including remembering the second to greatest element.

E max = values[0];
E secondMax = values[0];

for (E element : elements) {
    if (element.compareTo(max) > 0) {
        secondMax = max;
        max = element;
    } else if (element.compareTo(secondMax) > 0) {
        secondMax = element;
    }
}

return secondMax;

Note that you need to remember the max element too, since you want to find an element that is not greater than max, but still greater than the rest.

Upvotes: 0

Machhindra Neupane
Machhindra Neupane

Reputation: 717

we need to sort an array on descending order you can use bubble sort, now we can get the last index value as highest number and second last index as second highest number. example.

class ReturnTwoHeighestNumber {
  public static void main(String...args) {
   int arr[] = {12,13,15,6,9,30,50,19};
   ReturnTwoHeighestNumber number = new ReturnTwoHeighestNumber();
   number.bubleSort(arr);
   number.printTwohighestNumber(arr)   
  }
  void bubleSort(int arr[]) {
  int n= arr.length;
   for(int i=0; j<n-1;i++) {
      for(int j=0;j<n-i-1; j++) {
         if(arr[j]> arr[j+1]) {
          int temp = arr[1];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
         }
      }
   }
  void printTwohighestNumber(int arr[]) {
    int n= arr.length;
    for(int j=0;j<n;++j) {
      System.out.print(arr[j]+" ");
      System.out.println();  
    }
     System.out.println("My first highest Number is "+ arr[arr.length-1]);
     System.out.println("My Second highest Number is "+arr[arr.length-2]);   
  }    

  } 
}

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40078

You can use Java 8 streams to remove duplicates and sort the array, and use length-1 and length-2 to get max and second max element from array

Integer intArray[] = { 13,13, 25, 46,25, 65, 12, 23};
    Double doubleArray[] = {1.2, 3.4, 1.1, 0.1, 5.6};
    String stringArray[] = {"H", "E", "L", "L", "O"};

   Integer[] s= Arrays.stream(intArray).sorted().distinct().toArray(Integer[]::new);
   System.out.println(Arrays.toString(s));
   int max = s[s.length-1];
   int max2 = s[s.length-2];

or if you just want to sort array then you should use Arrays.sort to sort array and get the max and second max element

Arrays.sort(intArray) 
int max = s[s.length-1];
int max2 = s[s.length-2];

Upvotes: 2

Related Questions