Find the Kth largest value in array using java
You are given with array and integer K, now you need to find the kth largest value in the array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class KthLargestValue { | |
public static int KLargestValue(int[] input1,int input2) | |
{ | |
int output=0; | |
Arrays.sort(input1); //sorted array in ascending order | |
int k=0; | |
int [] largeToSmall=new int[input1.length]; | |
for(int i=input1.length-1;i>=0;i--){ | |
largeToSmall[k]=input1[i]; //sorting array in descending order | |
k++; | |
} | |
output=largeToSmall[input2-1]; //getting kth largest value from array. | |
return output; | |
} | |
public static void main(String [] args){ | |
Scanner in = new Scanner(System.in); | |
int output = 0; | |
int ip1_size = 0; | |
ip1_size = Integer.parseInt(in.nextLine().trim()); | |
int[] ip1 = new int[ip1_size]; | |
int ip1_item; | |
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) { | |
ip1_item = Integer.parseInt(in.nextLine().trim()); | |
ip1[ip1_i] = ip1_item; | |
} | |
int ip2 = Integer.parseInt(in.nextLine().trim()); | |
output = KLargestValue(ip1,ip2); | |
System.out.println(String.valueOf(output)); | |
in.close(); | |
} | |
} |
Input
5 ----Array size
11 -----------------
4 |
3 |Array elements
1 |
2 -----------------
3 ----K th Value.
Output: 3 (Since it is looking 3rd largest value in the array)
Input:
5
4
3
5
9
1
1
Output: 9 (Since it is looking for 1st largest value in the array)
5 ----Array size
11 -----------------
4 |
3 |Array elements
1 |
2 -----------------
3 ----K th Value.
Output: 3 (Since it is looking 3rd largest value in the array)
Input:
5
4
3
5
9
1
1
Output: 9 (Since it is looking for 1st largest value in the array)
Comments
Post a Comment