Java—快排陷阱
package work;
public class QuickSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] test= { 36, 25, 48, 12, 65, 25, 43, 58, 76, 32 };
System.out.println("快速排序之前:");
for(int i:test) {
System.out.print(i+" ");
}
System.out.println();
getDivideIndex(test, 0, test.length-1);
System.out.println("一趟快速排序之后:");
for(int i:test) {
System.out.print(i+" ");
}
System.out.println();
quickSort(test, 0, test.length-1);
System.out.println("快速排序之后:");
for(int i:test) {
System.out.print(i+" ");
}
}
public static int getDivideIndex(int[] arrays,int low,int high) {
// int oldLow=low; //如果哨兵选择为low,则下面的while循环要把high--那个放到上边
// int baseValue=arrays[low];
int oldHigh=high;
int baseValue=arrays[high]; //如果哨兵选择为high,则下面的while循环要把low++那个放到上边
while(low<high) {
while(low<high&&arrays[low]<=baseValue) {
low++;
}
while(low<high&&arrays[high]>=baseValue) {
high--;
}
if(low<high) {
Swap(arrays, low, high);
}
}
//if(low==high) {
// arrays[oldLow]=arrays[low];
// arrays[low]=baseValue;
arrays[oldHigh]=arrays[high];
arrays[high]=baseValue;
//}
return low;
}
public static void Swap(int[] arrays,int low,int high) {
int temp=0;
temp=arrays[high];
arrays[high]=arrays[low];
arrays[low]=temp;
}
public static void quickSort(int[] arrays,int low,int high) {
if(low<high) {
int dicideIndex=getDivideIndex(arrays, low, high);
quickSort(arrays, low, dicideIndex-1);
quickSort(arrays, dicideIndex+1, high);
}
}
}
//如果哨兵选择为low,则下面的while循环要把high–那个放到上边
//如果哨兵选择为high,则下面的while循环要把low++那个放到上边
因为你想想,如果哨兵选择为low,同时又把low++的循环放到上边,那么每次都是先进入low++的循环,当最后一次arrays[low]和arrays[high]交换之后,(假设是升序排序,升降序都无所谓)这个时候arrays[high]>arrays[low],然后再进入low++的循环low+=1;这时候low==high,然后出来将low位置的值与哨兵进行交换,但是此时low指向的是high位置的值,大于哨兵的值,交换之后,将low的值放到哨兵的位置上,那么哨兵前面的值就不满足都小于哨兵了,因此快排失效。这一点要格外注意!