import java.util.Arrays;
public class QuickSortMidNumber {
public static void main(String[] args) {
int arr[] = {5, 6, 9, 2, 3, 1, 4, 12, 7, 11, 10};
int val = quickMidNumber(arr, 0, arr.length - 1);
System.out.println(val);
}
/**
* 快排思想求中位数
* 时间复杂度:O(n)
*/
private static int quickMidNumber(int[] nums, int start, int end) {
int left = start;
int right = end;
int point = nums[start];
while (true) {
while (left < right && nums[right] >= point) right--; // 移动指针
while (left < right && nums[left] <= point) left++;
if (left == right) { // 循环结束条件
break;
} else { // 交换左右
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
nums[start] = nums[left]; // 数据给最左端
nums[left] = point;
System.out.println(Arrays.toString(nums) + "---left" + left);
/**
* [3, 4, 1, 2, 5, 9, 6, 12, 7, 11, 10]---left4
* [3, 4, 1, 2, 5, 7, 6, 9, 12, 11, 10]---left7
* [3, 4, 1, 2, 5, 6, 7, 9, 12, 11, 10]---left6
* [3, 4, 1, 2, 5, 6, 7, 9, 12, 11, 10]---left5
* 6
*/
if (left == (nums.length - 1) / 2) {
return nums[left];
} else if (left > (nums.length - 1) / 2) {
return quickMidNumber(nums, start, left - 1);
} else {
return quickMidNumber(nums, left + 1, end);
}
}
}
快排思想求中位数
最新推荐文章于 2024-05-07 06:48:00 发布