假如有个数组a
-
找到基准temp,即第一个数
-
从这里开始循环,令i为头位置,j为尾位置
2.1 从尾到头:如果该数比基准大,就继续向前;如何比基准小,就让a[i]=a[j]。
2.2从头到尾:如果该数比基准小,就继续向后;如果该数比基准大,就让a[j]=a[i],并让a[i]=temp。 -
直到i=j时结束第一轮的排序,此时数组a以temp为基准,左边都是比temp小的数,右边都是比temp大的数。接着对temp左右的子数组像上面那样排序,直到(start=end)开始等于结束,子数组里只剩一个数。
代码如下
public class QuickSort {
public static int[] quickSort(int[] array, int start, int end){
if (start < end){
int i = start;
int j = end;
int temp = array[i];
while (i < j){
while (i < j && temp <= array[j] ){
j--;
}
array[i] = array[j];
while (i < j && temp >= array[i]){
i++;
}
array[j] = array[i];
array[i] = temp;
}
quickSort(array, start, i-1);
quickSort(array,j+1, end);
}
return array;
}
public static void main(String[] args) {
int[] array = {3,45,78,64,52,11,64,55,99,11,18};
int[] ints = quickSort(array, 0, array.length - 1);
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i]+",");
}
}
}