有生之年希望快速排序不要再写错了。。
注意一点,左右指针在往中间靠拢的时候,要先处理上边界。如果先处理下边界,那样的话是行不通的。举个例子就清楚些了。拿数组5,4,3,7,6,8 为例。例举了两个partition的过程。
代码:
package codes;
public class MyQuickSort {
public static void main(String[] args) {
int [] nums = {5,4,3,7,6,8};
new MyQuickSort().quickSort(nums, 0, nums.length-1);
for( int i=0;i< nums.length;i++){
System.out.print(nums[i]+" ");
}
}
public void quickSort(int [] nums, int low, int high){
int q = partition(nums,low,high);
//这里漏了,找了十分钟
if( low < high){
quickSort(nums,low,q-1);
quickSort(nums,q+1,high);
}
}
public int partition(int [] nums , int low , int high){
int flag = nums[low];
//int left = low,right = high;
while(low<high){
//!!
while( nums[high]>=flag && low<high ) high--;
nums[low] =nums[high];
while( nums[low]<=flag && low<high) low++;
nums[high] =nums[low];
}
nums[low]=flag;
return low;
}
}