Printing the 2 highest numbers in an Array

find second largest number in array in c
find second largest number in array c++
c program to find largest and second largest number in an array
find 3 largest numbers in an array in c
find second largest number in array javascript
c++ program to find second largest number without using array
find second largest number in array python
algorithm to find largest number 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.

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];

Find the largest three elements in an array, Given an array with all distinct elements, find the largest three elements. second = third = -∞ 2) Iterate through all elements of array. a) Let current array element elements in an array. import sys. # Function to print three largest. # elements. Write a program to find top two maximum numbers in a array. Write a program to sort a map by value. Write a program to find common elements between two arrays. How to swap two numbers without using temporary variable? Write a program to print fibonacci series. Write a program to find sum of each digit in the given number using recursion.

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]);   
  }    

  } 
}

Printing the 2 highest numbers in an Array, 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  A Better Solution is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O (n). A more Efficient Solution can be to find the second largest element in a single traversal.

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.

Write a program to find top two maximum numbers in a array., Write a program to find top two maximum numbers in a array. - Java Interview 2​. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. package Write a program to print all permutations of a given string. Implement  Enter total number of elements: 8 Enter Number 1: 23.4 Enter Number 2: -34.5 Enter Number 3: 50 Enter Number 4: 33.5 Enter Number 5: 55.5 Enter Number 6: 43.7 Enter Number 7: 5.7 Enter Number 8: -66.5 Largest element = 55.5 This program takes n number of elements from user and stores it in array arr[].

C++ Program to find second Largest element in an array, The program asks the user to enter the value of n, which is the number of for (​int i = 2; i< n ; i ++) { /* If the current array element is greater than largest * then the Output: Enter number of elements: 5 Enter Array Element1: 12 Enter Array  Enter number of elements you want to enter: 5 Enter Element 1: 19 Enter Element 2: 21 Enter Element 3: 3 Enter Element 4: 89 Enter Element 5: 13 Largest element in array is: 89. User enters 5 which means the loop that stores the input values into the array runs 5 times, first entered value is stored in num [0], second in num [1] and so on.

C Program to Find Largest Element in an Array, Output Enter the number of elements (1 to 100): 5 Enter number1: 34.5 Enter number2: the first two elements of array are checked and the largest of these two  We can find the largest number in an array in java by sorting the array and returning the largest number. Let's see the full example to find the largest number in java array. Let's see another example to get largest element in java array using Arrays. Let's see another example to get largest number in java array using collections.

C Program to Find the Largest Number in an Array, This is a C Program to find the largest number in an array. Problem Description here 12,56,34,78,100 are the elements at indices 0,1,2,3,4 respectively */. In this example Prev - C Program to Print the kth Element in the Array. » Next - C  Step 1: Iterate the given array. Step 2 (first if condition arr[i] > largest):. If current array value is greater than largest value then. Move the largest value to secondLargest and make

Comments
  • You need to remember both at the same time when traversing, not only the highest. But also the second highest candidate. Alternatively, sort the array and pick the second element. Or do a 2-sort (k-sort). Or you use your method to identify the highest element, remove it, and identify the highest again.
  • Arrays.sort(elements); - Numbers are, by default, sorted ascending. elements[0] is not the greatest, but the smallest element. The greatest is elements[elements.length - 1] and the second to greatest is elements[elements.length - 2]. Please do some debugging, just add some System.out.println(...) to your code to inspect it. You could have easily found that out yourself.
  • ok this makes a lot of sense! thank you! And just to clarify, if I remove that element (the highest one) I could just redo what I already did and return the 2nd largest correct?
  • you can remove elements from array
  • @Deadpool how exactly do I remove an element from an array?
  • Note that a full sort is not required to get the second to greatest element.