Partitions the array around a pivot. @param arr the input array @param begin the starting index @param end the ending index @param num the pivot element @return the range where the pivot is located
(int[] arr, int begin, int end, int num)
| 111 | * @return the range where the pivot is located |
| 112 | */ |
| 113 | public static int[] partition(int[] arr, int begin, int end, int num) { |
| 114 | int small = begin - 1; |
| 115 | int cur = begin; |
| 116 | int big = end + 1; |
| 117 | while (cur != big) { |
| 118 | if (arr[cur] < num) { |
| 119 | swap(arr, ++small, cur++); |
| 120 | } else if (arr[cur] > num) { |
| 121 | swap(arr, --big, cur); |
| 122 | } else { |
| 123 | cur++; |
| 124 | } |
| 125 | } |
| 126 | return new int[] {small + 1, big - 1}; |
| 127 | } |
| 128 | |
| 129 | /** |
| 130 | * Finds the median of the elements between the specified range. |