当我运行我想要快速排序的代码时,我发现实现中存在问题。当我选择一个数据透视图时,它最终会失效,因为如果它作为一个数据透镜,它会选择一个数组中的最小元素,并且该元素在数组中出现两次,它将以无限循环结束。如果我在while循环外面左右放置它就没有用。
我的代码:
import java.util.*;
public class QuickSort {
static int[] stev = {8, 3, 1, 6, 4, 2, 9, 1};
public static void main(String[] args) {
sort(0, stev.length - 1);
System.out.println(Arrays.toString(stev));
}
@SuppressWarnings("empty-statement")
static int divide(int l, int r, int p) {
int left = 0;
int right = stev.length-1;
while (true) {
while (stev[left] < p) {
left++;
}
while (right >= l && stev[right] > p) {
right--;
}
if (left >= right) {
break;
} else {
System.out.println(Arrays.toString(stev));
int tmp = stev[left];
stev[left] = stev[right];
stev[right] = tmp;
left++;
right--;
}
System.out.println(Arrays.toString(stev));
int tmp = stev[left];
stev[left] = stev[r];
stev[r] = tmp;
return left;
}
static void sort(int left, int right) {
if (right - left <= 0) {
return;
}
int p = divide(left, right, stev[right]);
//System.out.println(Arrays.toString(stev));
sort(left, p - 1);
sort(p + 1, right);
}
}
输出:
[8, 3, 1, 6, 4, 2, 9, 1]
[1, 3, 1, 6, 4, 2, 9, 8]
[1, 3, 1, 6, 4, 2, 9, 8]
[1, 1, 3, 6, 4, 2, 9, 8]
[1, 1, 8, 6, 4, 2, 9, 3]
[1, 1, 8, 6, 4, 2, 9, 3]
[1, 1, 8, 6, 4, 2, 9, 3]
[1, 1, 3, 6, 4, 2, 9, 8]
[1, 1, 3, 6, 4, 2, 9, 8]
[1, 1, 3, 2, 4, 6, 9, 8]
[1, 1, 3, 2, 8, 6, 9, 4]
[1, 1, 3, 2, 4, 6, 9, 8]
[1, 1, 3, 2, 4, 8, 9, 6]
[1, 1, 3, 2, 4, 6, 9, 8]
[1, 1, 3, 2, 4, 6, 8, 9]
我认为问题出在分区功能的某个地方,但我无法找到它。