快速排序的原理:每次将序列以一个值为界限分成两组,再将得到的两个序列分别以一个界限分成两组变成四组这样一直分下去。
int[] a = {11,222,44,63,84,11,24,53,123,25,98,76,34};
第一步:以34将数组a分成两组 11, 25, 24, 11 34, 63, 44, 53, 123, 222, 98, 76, 84
第二步:以11将11, 25, 24, 11分为两组 11, 11, 24, 25。以84将34, 63, 44, 53, 123, 222, 98, 76, 84分为两组34, 63, 44, 53, 76, 84 98, 123, 222。
这样一直循环下去直到不能再分。
package test;
import java.util.Arrays;
public class QuickSort {
public void partition(int[] arrays, int left, int right) {
if ( right == 0 || left >= right){
return;
}
int oldLeft = left;
int oldRight = right;
int median = arrays[right];
right = right -1;
// 拿出数组最后一个词作为界限,数组的最后一个本身不参与比较
while (left<right) {
while (left < right && arrays[left] < median){left++;};
while (left < right && arrays[right] >= median){right--;};
int temp = arrays[right];
arrays[right] = arrays[left];
arrays[left] = temp;
}
if(arrays[oldRight] < arrays[right]){
arrays[oldRight] = arrays[right];
arrays[right] = median;
}
partition(arrays,oldLeft,left);
partition(arrays,right+1,oldRight);
}
public static void main(String[] args) {
int[] a = { 11, 222, 44, 63, 84, 11, 24, 53, 123, 25, 98, 76, 34 };
new QuickSort().partition(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
}