In this example, we’ll find Kth smallest element in unsorted array:
Input:
int[] arr1 = { 0, 10, 31, 19, 8 };
int k = 2;
Output:
8
K=2 means we want to find 2nd smallest number in the given array and to find the value it’s important to sort the array in the first place.
1. Java
Using Arrays.sort() method:
import java.util.Arrays;
public class FindKthSmallestElementInUnsortedArray {
public static void main(String[] args) {
int unSortedArray[] = { 0, 10, 31, 19, 8 };
findNumber(unSortedArray, 2);
}
private static void findNumber(int arr[], int k) {
Arrays.sort(arr); /
// Kth smallest will be k-1. Suppose K = 4 then in sorted array element on index
// position 3 will be Kth element. i.e k-1 (because indexing starts from 0)
System.out.println(arr[k - 1]);
}
}
Output:
8
Using Insertion Sort:
public class FindKthSmallestElementInUnsortedArray {
public static void main(String[] args) {
int unSortedArray[] = { 13, 9, 4, 21, 1, 17 };
findNumber(unSortedArray, 2);
}
private static void findNumber(int arr[], int k) {
sortElement(arr);
// Kth smallest will be k-1. Suppose K = 4 then in sorted array element on index
// position 3 will be Kth element. i.e k-1 (because indexing starts from 0)
System.out.println(arr[k - 1]);
}
private static int[] sortElement(int[] arr) { // insertion sort
for (int i = 1; i < arr.length; i++) {
int element = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > element) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = element;
}
return arr;
}
}
Output:
4
Complete Java Solutions can be found here: Github Link