Finds the median of medians as the pivot element. @param arr the input array @param begin the starting index @param end the ending index @return the median of medians
(int[] arr, int begin, int end)
| 92 | * @return the median of medians |
| 93 | */ |
| 94 | public static int medianOfMedians(int[] arr, int begin, int end) { |
| 95 | int num = end - begin + 1; |
| 96 | int offset = num % 5 == 0 ? 0 : 1; |
| 97 | int[] mArr = new int[num / 5 + offset]; |
| 98 | for (int i = 0; i < mArr.length; i++) { |
| 99 | mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); |
| 100 | } |
| 101 | return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * Partitions the array around a pivot. |