package com.bdqn.suanfa;
public class QickSort {
public static void main(String[] args) {
int array[] = {11, 77,22, 1, 2, 3, 12, 2,88, 103,21, 32,99,102, 12,99,44,33,22,11,333,444,3332,12,999,1000,3000,2000};
//int array[] = {11, 77,22, 1, 2, 3, 12, 2,88}; //短数组为了debug 调试使用
long startTime = System.currentTimeMillis(); // 获取开始时间
int[] ints = quickSort(array, 0, array.length - 1);
long endTime = System.currentTimeMillis(); // 获取结束时间
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
for (int i = 0; i <ints.length-1 ; i++) {
System.out.print(ints[i]+",");
}
}
public static int partition(int array[], int low, int high) {
int temp = array[low]; //定义 一个基准值
int i = low; //开始时数组最左侧的位置(元素的下标)
int j = high; //开始时数组最右侧的位置(元素的下标)
while (i <j) { //这里的判断条件 也可以写成 i !=j
/**
* 1.先从右边往左找一个小于基准位的数
* 2.当右边的哨兵位置所在的数>基准位的数时,则继续往左找
* 3,继续往左找的同时 j -= 1 ,索引减少1
* 4.找到后会跳出while循环
*/
while (i < j && array[j] > temp) {
j--;
}
/**
* 找到比基准值小的时候,判断,交换值
*/
if (i < j) {
array[i] = array[j];
i++;
}
while (i < j && array[i] < temp) {
i++;
}
if (i < j) {
array[j] = array[i];
j--;
}
array[i] = temp;
}
array[i] = temp;
//注意:这里 return i 和 return low 都可以达到预期效果,但两者的执行效率,相差很大
return i;
}
public static int[] quickSort(int a[], int low, int high) {
if (low < high) {
int i = partition(a, low, high);
quickSort(a, low, high - 1);
quickSort(a, i + 1, high);
}
return a;
}
}