MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / BFPRT

Class BFPRT

src/main/java/com/thealgorithms/others/BFPRT.java:9–178  ·  view source on GitHub ↗

The BFPRT (Median of Medians) algorithm implementation. It provides a way to find the k-th smallest element in an unsorted array with an optimal worst-case time complexity of O(n). This algorithm is used to find the k smallest numbers in an array.

Source from the content-addressed store, hash-verified

7 * This algorithm is used to find the k smallest numbers in an array.
8 */
9public final class BFPRT {
10 private BFPRT() {
11 }
12
13 /**
14 * Returns the k smallest elements from the array using the BFPRT algorithm.
15 *
16 * @param arr the input array
17 * @param k the number of smallest elements to return
18 * @return an array containing the k smallest elements, or null if k is invalid
19 */
20 public static int[] getMinKNumsByBFPRT(int[] arr, int k) {
21 if (k < 1 || k > arr.length) {
22 return null;
23 }
24 int minKth = getMinKthByBFPRT(arr, k);
25 int[] res = new int[k];
26 int index = 0;
27 for (int value : arr) {
28 if (value < minKth) {
29 res[index++] = value;
30 }
31 }
32 for (; index != res.length; index++) {
33 res[index] = minKth;
34 }
35 return res;
36 }
37
38 /**
39 * Returns the k-th smallest element from the array using the BFPRT algorithm.
40 *
41 * @param arr the input array
42 * @param k the rank of the smallest element to find
43 * @return the k-th smallest element
44 */
45 public static int getMinKthByBFPRT(int[] arr, int k) {
46 int[] copyArr = copyArray(arr);
47 return bfprt(copyArr, 0, copyArr.length - 1, k - 1);
48 }
49
50 /**
51 * Creates a copy of the input array.
52 *
53 * @param arr the input array
54 * @return a copy of the array
55 */
56 public static int[] copyArray(int[] arr) {
57 int[] copyArr = new int[arr.length];
58 System.arraycopy(arr, 0, copyArr, 0, arr.length);
59 return copyArr;
60 }
61
62 /**
63 * BFPRT recursive method to find the k-th smallest element.
64 *
65 * @param arr the input array
66 * @param begin the starting index

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected