Skip to main content

Java program to find the Kth largest element in an array of positive integers


Problem:

Given an array, print k largest elements from the array.  The output elements should be printed in decreasing order.

 Input:

 The first line of input contains an integer T denoting the number of test cases.
 The first line of each test case is N and k, N is the size of array and K is the largest elements to be returned.
 The second line of each test case contains N input C[i].

 Output:

 Print the k largest element in descending order.

 Constraints:

 1 ≤ T ≤ 100
 1 ≤ N ≤ 100
 K ≤ N
 1 ≤ C[i] ≤ 1000

 Example:

 Input:
 2
 5 2
 12 5 787 1 23
 7 3
 1 23 12 9 30 2 50

 Output:
 787 23
 50 30 23


Solution program below:

package test;

import java.util.Comparator;
import java.util.Scanner;

import static java.util.Arrays.sort;

public class KLargestElement {

    public static void sortNumberUpToGivenNumber(Integer[] inputArray, int K) {
        sort(inputArray, new Comparator<Integer>(){
            @Override
            public int compare(Integer i1, Integer i2) {
                return i2.compareTo(i1);//sort in reverse
            }
        });
        for (int a = 0; a < K; a++)
            System.out.print(inputArray[a] + " ");
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of test cases: ");
        int T = scanner.nextInt();
        for(int i = 0; i < T; i++) {
            int N = scanner.nextInt();
            int K = scanner.nextInt();
            // create an array of size N
            Integer[] array = new Integer[N];
            //store numbers and sort upto the given number
            for (int j = 0; j < N; j++) {
                array[j] = scanner.nextInt();
            }
            if(K <= N)
                sortNumberUpToGivenNumber(array, K);
            else
                System.out.println("Wrong entry! Please try again.");
        }
    }
}


Sample Input:
 2
 5 2
 12 5 787 1 23
 7 3
 1 23 12 9 30 2 50

Output:
 787 23
 50 30 23



Comments

Popular posts from this blog

Struts2 and Hibernate Example using Annotation

Hi Guys, Today we are going to create an example using Struts2 and Hibernate using Annotation. For the database, we are going to use MySQL. This example will register a record for a user in the mysql database, which later will be used to login to the application. First of all we need to create our database table in MySQL. Log into your mysql database and type the following command to create a database in the mysql prompt. create database mydb; Use the above created database to create table. use mydb; Now we need to create a database table named "users". create table users( uid int primary key auto_increment, uname char(15), password char(20), email char(20), phone long, city char(15)); Now to create this application, we are going to use eclipse. Open your eclipse and create a dynamic web project. Put the following jars related to Struts2 and Hibernate in the WEB-INF/lib folder Now create the following packages in the src folder for the ...

Java program to create staircase

Observe that its base and height are both equal to  , and the image is drawn using  #  symbols and spaces.  The last line is not preceded by any spaces. Write a program that prints a staircase of size  . Input Format A single integer,  , denoting the size of the staircase. Output Format Print a staircase of size   using  #  symbols and spaces. Note : The last line must have   spaces in it. package com.rohan.test; import java.util.Scanner; public class StaircaseTest {     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();                  for(int i = 0; i< n; i++) {         for(int k = 0; k < n; k++) {         if(k < n-i-1)         System.out.p...

Java program to print the maximum hourglass value of the matrix

Context   Given a    2D Array ,  : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in   to be a subset of values with indices falling in this pattern in  's graphical representation: a b c d e f g There are   hourglasses in  , and an  hourglass sum  is the sum of an hourglass' values. Task   Calculate the hourglass sum for every hourglass in  , then print the  maximum  hourglass sum. Note:  If you have already solved the Java domain's  Java 2D Array  challenge, you may wish to skip this challenge. Input Format There are   lines of input, where each line contains   space-separated integers describing  2D Array   ; every value in   will be in the inclusive range of   to  . Constraints Output Format Print the largest (maximum) hourglass sum f...