privatestaticint[] partition(int[] arr, int begin, int end, int pivot){ int L= begin-1; int R= end + 1; int cur = begin; while(cur!=R){ if(arr[cur]>pivot){ swap(arr, cur, --R); } elseif(arr[cur]<pivot){ swap(arr, cur++, ++L) } else{ cur++; } } returnnewint[]{L+1, R-1}; }
privatestaticintmedianOfMedians(int[] arr, int begin, int end){ int num = end - begin +1; int offset = num % 5 ==0 ? 0 : 1; int[] medians = newint[num/5 + offset]; for(int i=0;i<medians.length; i++){ int beginI = begin+i*5; int endI = beginI + 4; medians[i] = getMedian(arr, beginI, Math.min(endI, end)); } return BFPRT(medians, 0, medians.length-1, medians.length/2); }
privatestaticint get Median(int[] arr, int begin, int end){ insertionSort(arr, begin, end); int sum = end+begin; int mid = (sum/2) + (sum%2); return arr[mid]; } privatestaticvoidinsertionSort(int[] arr, int begin, int end){ if (begin>=end) return; for(int i=begin+1; i<=end; i++){ for(int j=i; j>begin; j--){ if(arr[j] < arr[j-1]){ swap(arr, j, j-1); }else{ break; } } } }
时间复杂度
最坏情况下是 $O(n)$
令 $T(n)$ 为所求的时间复杂度,则:
$T(\frac n 5)$ 来自 GetPivotIndex(),n 个元素,5 个一组,共有 $⌊\frac n5⌋$ 个中位数;