import java.util.Arrays;
/**
*
* 快速排序通过一个切分元素将数组分为两个子数组,左子数组小于等于切分元素,右子数组大于等于切分元素.
* 将这两个子数组排序也就将整个数组排序了。
*
* 最好时间O(nlogn);平均时间O(nlogn); 最坏时间O(n^2); 辅助存储O(logn) 不稳定;
*
*/
public class QuickSort {
public static void main(String[] args) {
int[] arr = new int[]{3,4,6,7,2,7,28,0};
System.out.println(Arrays.toString(arr));
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int start, int end) {
if (start>=end) {
return;
}
// 把数组中的第零个数字作为标准数
int index = arr[start];
// 记录要排序的下标
int low = start;
int high = end;
//循环找比标准数大的数和比标准数小的数
while (low<high) {
//右边的数字比标准数大
while ( low<high && arr[high] >=index ) {
high--;
}
//使用右边的数字替换左边的数
arr[low] = arr[high];
//如果左边的数字比标准数小
while(low<high && arr[low] <= index) {
low++;
}
arr[high]=arr[low];
}
//把标准数据赋给低所在的位置的元素(此时 low=high)
arr[low]=index;
//处理所有的小的数字
quickSort(arr,start,low-1);
//处理所有的大的数字
quickSort(arr,low+1,end);
}
}
快速排序
最新推荐文章于 2021-12-15 23:25:50 发布