Java Program to Find the kth Element in an Array
In this post, you will learn how to find the kth element in an array using the Java programming language.
import java.util.Arrays;
import java.util.Scanner;
public class KthElementFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();
// Input: Array elements
int[] array = new int[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
// Input: Position k
System.out.print("Enter the value of k: ");
int k = scanner.nextInt();
if (k > 0 && k <= n) {
// Sort the array (if you want the kth smallest or largest)
Arrays.sort(array);
// Output: kth element in the sorted array
System.out.println("The " + k + "th element in the array is: " + array[k - 1]);
} else {
System.out.println("Invalid value of k.");
}
scanner.close();
}
}
Output of the above code:
Enter the size of the array: 6
Enter the elements of the array:
89 82 58 19 63 50
Enter the value of k: 4
The 4th element in the array is: 63
Code Explanation:
1. Input the Array: The program first prompts the user to input the size of the array and then the elements of the array.
2. Input k: It then asks for the position k (1-based index) of the element you want to find.
3. Sort the Array: The program sorts the array. (This step is necessary if you want to find the kth smallest or kth largest element.)
4. Retrieve the kth Element: The program retrieves and prints the kth element from the sorted array.
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number