(low <= high && list[low] <= pivot)
?
? ? ? ? ? ? ? ? low++;
?
? ? ? ? ? ??
?
? ? ? ? ? ? while(low <= high && list[high] > pivot){
?
? ? ? ? ? ? ? ? high--;
?
? ? ? ? ? ? }
?
? ? ? ? ? ? if(high > low){
?
? ? ? ? ? ? ? ? int temp = list[high];
?
? ? ? ? ? ? ? ? list[high] = list[low];
?
? ? ? ? ? ? ? ? list[low] = temp;
?
? ? ? ? ? ? }
?
? ? ? ? }
?
//经过上面一个循环之后,下标小于low的元素均小于pivot,小标大于high的元素均大于pivot
?
?
?
? ? ? ? //将high的下标从后向前遍历,直到找到当前下标的值小于等于pivot为止
?
? ? ? ? while(high > first && list[high] >= pivot){
?
? ? ? ? ? ? high--;
?
? ? ? ? }
?
? ? ? ??
?
? ? ? ? if(pivot > list[high]){//if成立,表示pivot的值不是集合中最小的值,此时将pivot的值放到list[high]的位置上
?
? ? ? ? ? ? list[first] = list[high];
?
? ? ? ? ? ? list[high] = pivot;
?
? ? ? ? ? ? return high;
?
? ? ? ? }else{ //此种情况表示,pivot为集合中最小的元素,因此,pivot值的小标也就是first
?
? ? ? ? ? ? return first;
?
? ? ? ? }
?
? ? }
?
quicksort()代码如下:
?
private static void quickSort(int[] list, int first, int last){
?
? ? ? ? if(last > first){
?
? ? ? ? ? ? int pivotIndex = partition(list,first,last);
?
? ? ? ? ? ? quickSort(list,first,pivotIndex -1);
?
? ? ? ? ? ? quickSort(list,pivotIndex+1,last);
?
? ? ? ? }
?
? ? }
?
此时,定义一个只有一个集合作为参数的公共方法:
?
public static void quickSort(int[] list){
?
? ? ? ? quickSort(list,0,list.length-1);
?
? ? }
?
?
?
?
?
测试代码:
?
public static void main(String[] args) {
?
? ? ? ? // TODO Auto-generated method stub
?
? ? ? ? int[] list = {12,3,2,1,5,2};
?
? ? ? ? quickSort(list);
?
? ? ? ? for(int temp : list){
?
? ? ? ? ? ? System.out.print(temp + " ");
?
? ? ? ? }
?
? ? ? ? System.out.println();
?
? ? }