Finding Kth Maximum Number from an Array in Java

The following program is used to find the Kth Maximum number from a given unsorted array. The approach on which this code is written uses sorting and then gives out the Kth  maximum number. This can be done without sorting too. At the end of the code, you will get a sorted array and hence it makes it easier to find the Kth  element.

Code:

import java.util.Arrays;
import java.util.Scanner;

class Kelement{
    
   static void sorting(int arr[]){
       int i,j;
       for(i=0;i<arr.length-1;i++){
           for(j=i+1;j<arr.length;j++){
               if(arr[i]<arr[j]){
                   int t=arr[j];
                   arr[j]=arr[i];
                   arr[i]=t;
               }
           }
       }
       System.out.println(Arrays.toString(arr));
   }
    public static void main(String[]args){
        Scanner s=new Scanner(System.in);
        System.out.println("Enter the Kth Element:");
        int k=s.nextInt();
                System.out.println("Enter number of elements in the array:");
        int n=s.nextInt();
        int arr[]=new int[n];
        for( int i=0;i<n;i++){
        arr[i]=s.nextInt();
        }
            sorting(arr);
            System.out.println(arr[k]);

        
                
    }
    
}

OUTPUT:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: