Find k maximum elements of array in original order | Java program to find k maximum elements of array in original order ; Function to print m Maximum elements ; Array to store the copy of the original array ; Sorting the array in descending order ; Traversing through original array and printing all those elements that are in first k of sorted array . goo . gl / uj5RCD Please refer https : for details of Arrays . binarySearch ( ) ; Driver code
import java . util . Arrays ; import java . util . Collections ; public class GfG { public static void printMax ( int arr [ ] , int k , int n ) { Integer [ ] brr = new Integer [ n ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; Arrays . sort ( brr , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < n ; ++ i ) if ( Arrays . binarySearch ( brr , arr [ i ] , Collections . reverseOrder ( ) ) >= 0 && Arrays . binarySearch ( brr , arr [ i ] , Collections . reverseOrder ( ) ) < k ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 50 , 8 , 45 , 12 , 25 , 40 , 84 } ; int n = arr . length ; int k = 3 ; printMax ( arr , k , n ) ; } }