Java实现快速排序无法正确排序,请求排查partition方法问题
快速排序实现错误排查:Partition方法返回值错误
你的快速排序核心问题出在partition方法的返回值上:
- 你在partition方法最后将pivot交换到了
i+1的位置,但返回的是i,这导致递归时的分界点错误。 - 正确的返回值应该是
i+1——因为这个位置才是pivot最终的正确索引,后续递归需要以此为界,分别排序左半部分(low到pi-1)和右半部分(pi+1到high)。
修正后的Partition方法
仅需修改返回值一行:
int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = (low-1); for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; // Swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; // 此处从i改为i+1 }
验证结果
修正后运行代码,输入数组{10, 7, 8, 9, 1, 5}会输出预期的排序结果:
Sorted array: 1 5 7 8 9 10
你尝试的不同pivot策略(首元素、尾元素等)本身没有问题,只要保证partition方法返回pivot的正确索引,就能正常工作。
内容的提问来源于stack exchange,提问作者Sasindi Wijethunga
相关产品推荐
相关产品推荐

