快速排序的基本思想:
采用分治策略,每一趟排序把一个指定的元素放到合理的位置,满足其左边的元素全部比它小(大),其右边的元素全部比它大(小),每一趟排序,指定当前排序的范围,介于low和high之间
递归的结束标志是low<=high
具体看算法实现:
public static void quickSort(int[] array,int low,int high){
if(high<=low){
return;
}
int index_low = low;
int index_high = high;
int cmp = array[index_low];
while(low<high){
while(array[high]>cmp&&low<high){
high--;
}
while(array[low]<=cmp&&low<high){
low++;
}
if(low<high){
int temp = array[high];
array[high] = array[low];
array[low] = temp;
for(int i:array){
System.out.print(i+" ");
}
System.out.println("");
}
}
int temp = array[low];
array[low] = array[index_low];
array[index_low] = temp;
for(int i:array){
System.out.print(i+" ");
}
System.out.println("");
quickSort(array,index_low,low-1);
quickSort(array,high+1,index_high);
}
测试:
public class CommonTest {
int[] array = {5,1,6,2,7,15,11,3,8,3,9,0};
@Test
public void testQuickSort(){
QuickSort.quickSort(array, 0, array.length-1);
}
}
每一趟的排序输出:
5 1 0 2 7 15 11 3 8 3 9 6
5 1 0 2 3 15 11 3 8 7 9 6
5 1 0 2 3 3 11 15 8 7 9 6
3 1 0 2 3 5 11 15 8 7 9 6
3 1 0 2 3 5 11 15 8 7 9 6
2 1 0 3 3 5 11 15 8 7 9 6
0 1 2 3 3 5 11 15 8 7 9 6
0 1 2 3 3 5 11 15 8 7 9 6
0 1 2 3 3 5 11 6 8 7 9 15
0 1 2 3 3 5 9 6 8 7 11 15
0 1 2 3 3 5 7 6 8 9 11 15
0 1 2 3 3 5 6 7 8 9 11 15
快速排序这种东西,光是理解了思想还不行,还要自己手动写出来,写个一两遍,两三遍,三四遍,就差不多能记住了。
主要是递归结束标志和每一趟循环结束标志比较难理解。