快速排序,采用分治策略,将数组A[n]分组进行递归快速排序。
1 6 4 7 0 5 2 8 3 9
左指针指向:7 右指针指向:9
1 6 4 3 0 5 2 8 7 9
左指针指向:3 右指针指向:7
1 6 4 3 0 5 2 7 8 9
左指针指向:7 右指针指向:8
左指针指向:7 右指针指向:7
0 6 4 3 1 5 2 7 8 9
左指针指向:0 右指针指向:1
0 1 4 3 6 5 2 7 8 9
左指针指向:1 右指针指向:6
左指针指向:1 右指针指向:1
0 1 2 3 6 5 4 7 8 9
左指针指向:2 右指针指向:4
0 1 2 3 4 5 6 7 8 9
左指针指向:4 右指针指向:6
左指针指向:4 右指针指向:4
左指针指向:2 右指针指向:2
左指针指向:5 右指针指向:5
左指针指向:8 右指针指向:8
步骤:
- 以A[0]为基准元素,将数组中比其小的元素放在其左边,比其大的放在其右边;
- 将基准元素左右的数组分别再进行步骤1(即递归)。
public class QuickSort {
/**
* <p>MethodName:main </p>
* <p>Description: </p>
* <p>@param args</p>
* <p>Return:void </p>
* @author Sunny
* @date 2016-9-26下午7:36:43
*/
public static void main(String[] args) {
int[] arr={7,6,4,9,0,5,2,8,3,1};
quickSort(arr,0,9);
}
public static void quickSort(int[] arr,int low,int high){
if(low>=high) return;
int l=low,h=high,t=arr[low];
while(l<h){
while(arr[l]<t) l++;
while(arr[h]>t) h--;
if(l<h){
ArrayUtils.exchangeElements(arr, l, h);
ArrayUtils.printArray(arr);
}
System.out.println("左指针指向:"+arr[l]+" 右指针指向:"+arr[h]);
}
quickSort(arr,low,h-1);
quickSort(arr,l+1,high);
}
}
/**
* <p>MethodName:main </p>
* <p>Description: </p>
* <p>@param args</p>
* <p>Return:void </p>
* @author Sunny
* @date 2016-9-26下午7:36:43
*/
public static void main(String[] args) {
int[] arr={7,6,4,9,0,5,2,8,3,1};
quickSort(arr,0,9);
}
public static void quickSort(int[] arr,int low,int high){
if(low>=high) return;
int l=low,h=high,t=arr[low];
while(l<h){
while(arr[l]<t) l++;
while(arr[h]>t) h--;
if(l<h){
ArrayUtils.exchangeElements(arr, l, h);
ArrayUtils.printArray(arr);
}
System.out.println("左指针指向:"+arr[l]+" 右指针指向:"+arr[h]);
}
quickSort(arr,low,h-1);
quickSort(arr,l+1,high);
}
}
结果展示:
1 6 4 9 0 5 2 8 3
7
左指针指向:1 右指针指向:7
左指针指向:1 右指针指向:7
1 6 4 7 0 5 2 8 3 9
左指针指向:7 右指针指向:9
1 6 4 3 0 5 2 8 7 9
左指针指向:3 右指针指向:7
1 6 4 3 0 5 2 7 8 9
左指针指向:7 右指针指向:8
左指针指向:7 右指针指向:7
0 6 4 3 1 5 2 7 8 9
左指针指向:0 右指针指向:1
0 1 4 3 6 5 2 7 8 9
左指针指向:1 右指针指向:6
左指针指向:1 右指针指向:1
0 1 2 3 6 5 4 7 8 9
左指针指向:2 右指针指向:4
0 1 2 3 4 5 6 7 8 9
左指针指向:4 右指针指向:6
左指针指向:4 右指针指向:4
左指针指向:2 右指针指向:2
左指针指向:5 右指针指向:5
左指针指向:8 右指针指向:8