Java 具有重复值的快速排序
我有一个用于快速排序的java代码,如果没有重复项,它就可以工作,但是如果有任何重复项,快速排序就会失败。例如,如果我想对{5,3,3,1,7}进行快速排序,我的代码将输出{1,3,3,7,5},我似乎不明白为什么会这样Java 具有重复值的快速排序,java,duplicates,quicksort,Java,Duplicates,Quicksort,我有一个用于快速排序的java代码,如果没有重复项,它就可以工作,但是如果有任何重复项,快速排序就会失败。例如,如果我想对{5,3,3,1,7}进行快速排序,我的代码将输出{1,3,3,7,5},我似乎不明白为什么会这样 public static void quickSort(Integer[] nums) { quickSort(nums, 0, nums.length-1); } private static void quickSort(Integer[] ary, int
public static void quickSort(Integer[] nums) {
quickSort(nums, 0, nums.length-1);
}
private static void quickSort(Integer[] ary, int lo, int hi) {
//pick num @ lo to be pivot
int pivot = lo;
int i = lo+1;
int j = hi;
if( lo==hi) {
return;
}
while(i <j) {
if(ary[i].compareTo(ary[pivot]) <=0 ) {
i++;
}
else if(ary[j].compareTo(ary[pivot]) >=0 ) {
j--;
}
else {
int temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}
}
if(i == hi && j == hi) {
if(ary[pivot].compareTo(hi) > 0) {
int temp = ary[pivot];
ary[pivot] = ary[hi];
ary[hi] = temp;
pivot = hi;
}
else {
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
}
}
if(lo < pivot -1) {
quickSort(ary, lo, pivot-1);
}
if(pivot +1 < hi) {
quickSort(ary, pivot+1, hi);
}
}
公共静态void快速排序(整数[]nums){
快速排序(nums,0,nums.length-1);
}
私有静态void快速排序(整数[]元,整数lo,整数hi){
//选择num@lo作为枢轴
int-pivot=lo;
int i=lo+1;
int j=hi;
如果(低==高){
返回;
}
而(i 0){
int-temp=ary[pivot];
ary[pivot]=ary[hi];
ary[hi]=温度;
pivot=hi;
}
否则{
int temp1=ary[pivot];
ary[pivot]=ary[i-1];
ary[i-1]=temp1;
枢轴=i-1;
}
}
如果(lo<枢轴-1){
快速排序(ary、lo、pivot-1);
}
如果(枢轴+1
如果有人能告诉我我做错了什么,我将不胜感激 如果要快速排序,请使用此站点的算法
它对我很有用,我认为解释很好。您好,我已经修改了您的代码,请查看相应的注释
private static void quickSort(Integer[] ary, int lo, int hi) {
//pick num @ lo to be pivot
int pivot = lo;
int i = lo+1;
int j = hi;
if( lo==hi) {
return;
}
//while(i <j) {
for(;;){//change from while to infinite for
while(ary[i].compareTo(ary[pivot]) <=0 && i<hi ) {//changed from if to while with boundary conditions
i++;
}
while(ary[j].compareTo(ary[pivot]) >0 && j>lo) { //change from if to while with boundary conditions and it is not >=0 only >
j--;
}
if(i<j){ //changed from else to if
int temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}else{//added else block
break;
}
}
//you didn't handled i>j condition properly i.e when i>j you need to swap pivot and i-1
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
//Not required
/*if(i == hi && j == hi) {
if(ary[pivot].compareTo(hi) > 0) {
int temp = ary[pivot];
ary[pivot] = ary[hi];
ary[hi] = temp;
pivot = hi;
}
else {
int temp1 = ary[pivot];
ary[pivot] = ary[i-1];
ary[i-1] = temp1;
pivot = i-1;
}
}*/
if(lo < pivot -1) {
quickSort(ary, lo, pivot-1);
}
if(pivot +1 < hi) {
quickSort(ary, pivot+1, hi);
}
}
private静态void快速排序(整数[]位,整数低位,整数高位){
//选择num@lo作为枢轴
int-pivot=lo;
int i=lo+1;
int j=hi;
如果(低==高){
返回;
}
//而(仅i=0>
j--;
}
如果它看起来不像快速排序。