Skip to content

Commit 2f0ad31

Browse files
author
m0a07xh
committed
Find kth smallest element in the given unsorted array
1 parent 64fc841 commit 2f0ad31

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package datastructure.array;
2+
3+
import util.AlgoUtils;
4+
import util.ArrayUtil;
5+
6+
/**
7+
* Find kth smallest element in the given unsorted array
8+
* @author Manjunath Asundi
9+
*/
10+
public class KthSmallest {
11+
12+
private static void buildMaxHeap(int arr[], int root, int n) {
13+
int largest = root;
14+
int left = (root * 2) + 1;
15+
int right = (root * 2) + 2;
16+
if (left <= n && arr[largest] < arr[left]) {
17+
largest = left;
18+
}
19+
if (right <= n && arr[largest] < arr[right]) {
20+
largest = right;
21+
}
22+
if (largest != root) {
23+
int temp = arr[root];
24+
arr[root] = arr[largest];
25+
arr[largest] = temp;
26+
buildMaxHeap(arr, largest, n);
27+
}
28+
}
29+
30+
private static int heapify(int[] arr, int k) {
31+
for (int i = (k - 1) / 2; i >= 0; i--) {
32+
buildMaxHeap(arr, i, k - 1);
33+
}
34+
35+
for (int i = k; i < arr.length; i++) {
36+
if (arr[i] < arr[0]) {
37+
AlgoUtils.swapByIndex(arr, i, 0);
38+
buildMaxHeap(arr, 0, k - 1);
39+
}
40+
}
41+
return arr[0];
42+
}
43+
44+
public static void main(String[] args) {
45+
int[][] twoDArr = new int[][] {
46+
ArrayUtil.constructRandomUniqueElementsArray(),
47+
ArrayUtil.constructRandomUniqueElementsArray(),
48+
ArrayUtil.constructRandomArray(),
49+
ArrayUtil.constructRandomUniqueElementsArray(),
50+
{ 1, 11, 3, 4, 8, 5, 9, 7, 10 },
51+
{ 12, 2, 13, 5, 8, 11, 9, 6, 10 },
52+
{ 13, 3, 15, 7, 8, 9, 11, 12 },
53+
{ 2, 4, 6, 8, 9, 3, 7 }
54+
};
55+
56+
for (int[] arr : twoDArr) {
57+
ArrayUtil.printArray(arr);
58+
int k = AlgoUtils.random(arr.length - 1) + 1;
59+
System.out.println((k) + "(st/nd/rd/th) smallest number = " + heapify(arr, k));
60+
System.out.println();
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)