In: Computer Science
Find the K'th smallest element in an unsorted array of integers.
Find the K'th largest element in an unsorted array of integers.
please make two separate methods in java
ANSWER:-
import java.util.*;
import java.util.Arrays;
import java.util.Collections;
/* Name of the class has to be "Main" only if the class is public.
*/
class Ideone
{
public static int kthSmallest(int [] arr,int k)
{
// Sort the given array
Arrays.sort(arr);
// Return k'th element in
// the sorted array
return arr[k-1];
}
public static int kthlargest(int [] arr,int k)
{
// Sort the given array
Arrays.sort(arr);
// Return k'th element in
// the sorted array
return arr[arr.length-k];
}
public static void main (String[] args)
{
Scanner sc=new
Scanner(System.in);
System.out.println("Enter the size
of the array : ");
int n=sc.nextInt();
int []arr=new int[n];
System.out.println("enter the array
elements : ");
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
System.out.println("enter the k
value : ");
int k=sc.nextInt();
System.out.println("kth smallest is
: "+kthSmallest(arr, k));
System.out.println("kth largest is
: "+kthlargest(arr, k));
}
}
OUTPUT
// If any doubt please comment