Write the Java code to find the kth-largest number in an array of size more than 1.000,000 in O(n). Assume k < logn
import java.util.*;
class KLarge {
public static int p;
public static void klargest(Integer[ ] arr, int k)
{
Arrays.sort(arr, Collections.reverseOrder());
for (int i = 0; i < k; i++)
p = arr[i];
System.out.println("The k-th largest element is ");
System.out.print(p);
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter size of array");
int n=s.nextInt();
Integer arr[]=new Integer[n];
System.out.println("Enter elements into the array");
for(int i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
System.out.println("The array is : ");
for(int i: arr)
{
System.out.print(i+" ");
}
System.out.println();
System.out.println("Enter the value of k to find k-th largest
number");
int k = s.nextInt();
klargest(arr, k);
}
}
Get Answers For Free
Most questions answered within 1 hours.