In: Computer Science
Write a program in Java with a Scanner.
Given an array and a number k where k is smaller than the size of the array, write a program to find the k'th smallest element in the given array.
It is given that all array elements are distinct.
Example:
Input: arr[] = {7,10,4,3,20,15}
k = 3
Output: 7
import java.util.Arrays; import java.util.Scanner; public class KthSmallestElement { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter all the numbers you want to put in array seperated by space: "); String line = in.nextLine(); String tokens[] = line.split("\\s+"); int arr[] = new int[tokens.length]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(tokens[i]); } System.out.print("Enter value of k: "); int k = in.nextInt(); while(k < 1 || k > arr.length) { System.out.print("Invalid value.\nEnter value of k: "); k = in.nextInt(); } // do k pass in for (int i = 0; i < k; i++) { // Last i elements are already in place for (int j = arr.length - 1; j > i; j--) { if (arr[j] < arr[j - 1]) { int l = arr[j]; arr[j] = arr[j-1]; arr[j-1] = l; } } } //System.out.println(Arrays.toString(arr)); System.out.println("Kth element of array: " + arr[k-1]); in.close(); } }