1、从待排序列中任取一个元素 (例如取第一个) 作为中心,所有比它小的元素一律前放,所有比它大的元素一律后放,形成左右两个子表;然后再对各子表重新选择中心元素并依此规则调整,直到每个子表的元素只剩一个。
2、代码
package SwapSort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data={49,38,65,97,76,13,27,50};
System.out.println(Arrays.toString(quickSort(data,0,7)));
}
public static int[] quickSort(int[] data,int low, int high){
if(low<high){
int pivot=partition(data,low,high);
quickSort(data,low, pivot-1);
quickSort(data,pivot+1,high);
}
return data;
}
public static int partition(int[] data, int low, int high) {
// TODO Auto-generated method stub
int base=data[low];
while(low<high){
while(low<high&&base<=data[high]){
--high;
}
data[low]=data[high];
while(low<high&&base>=data[low]){
++low;
}
data[high]=data[low];
}
System.out.println(low+" "+high);
data[low]=base;
System.out.println(Arrays.toString(data));
return low;
}
}
3、运行结果
[27, 38, 13, 49, 76, 97, 65, 50]
[13, 27, 38, 49, 76, 97, 65, 50]
[13, 27, 38, 49, 50, 65, 76, 97]
[13, 27, 38, 49, 50, 65, 76, 97]
[13, 27, 38, 49, 50, 65, 76, 97]