快速排序算法的基本特性
时间复杂度:O(n*lgn)最坏:O(n^2)
空间复杂度:O(n*lgn)
不稳定。
快速排序是一种排序算法,对包含n个数的输入数组,平均时间为O(nlgn),最坏情况是O(n^2)。
通常是用于排序的最佳选择。因为,基于比较的排序,最快也只能达到O(nlgn)。
快速排序算法的程序实现(以数组第一个元素为主元)
我的另外一篇博客也讨论了快排的程序实现,两者有所不同,可以对比理解点击打开链接
package quickSort;
public class QuickSort {
static int arr[] = { 23, 6, 15, 8, 33, 2, 75,16,5};
public static void main(String[] args) {
quickSort(arr, 0, 8);
}
public static void quickSort(int[] arr, int low, int high) {
/*
* arr[low]作为low到high之间的第一个数值
* 在第一次赋值变动中会被覆盖,以此需要事先摘出来(给temp),以便最后一次赋值操作用
* 最后一次赋值操作完成后,数组将形成这样的格局:在temp位置的左边的数都小于temp,在temp右边的数都大于temp
*/
int temp = arr[low];
/*
* l记录low的大小,h记录high的大小,作为下次迭代的两头
*/
int l = low;
int h = high;
while (high > low) {
/*
* 从数组的最右侧向左移动,找到小于第一个小于或等于temp的数
* 找到后赋到low的位置
* low的位置向右移一位,也就是low++
*/
while (high > low) {
if (arr[high] > temp) {
high--;
} else {
arr[low] = arr[high];
low++;
break;
}
}
/*
* 从数组的最左侧向右移动,找到第一个大于temp的数,
* 然后附到high的位置,此时的high位置正是上面找到第一个小于temp的数的位置,正好覆盖过去
* 注意两个while的顺序不能变
*
*/
while (high > low) {
if (arr[low] <= temp) {
low++;
} else {
arr[high] = arr[low];
high--;
break;
}
}
}
System.out.println();
arr[low] = temp;
System.out.println();
System.out.println(
"用来比较的temp值是"+arr[low] + " 此时的l是" + l + " 此时的low是 " + low + " 此时的high是 " + high + " 此时的h是 " + h);
each(arr);
if (l < low - 1) {
quickSort(arr, l, low - 1);
}
if (high + 1 < h) {
quickSort(arr, high + 1, h);
}
}
public static void each(int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
}
}