0%

快速排序

简述

快速排序使用分治理念,将目标数组每次划分为左右两个区间分而治之。因而他也是一种不稳定排序算法,最坏情况下,每次选择的基准都是分区内最小或最大数,造成左/右分区为空,这种情况下,时间复杂度与冒泡排序相同,等于O(n^2)

Talk is cheap, show me the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class QuickSort {

/**
* a[] 目标数组
* low 低位
* hight 高位
**/
public static void sort(int a[], int low, int hight) {
int i, j, index;
if (low > hight) {
return;
}
//左分区起始位
i = low;
//右分区结束位
j = hight;
// 用子表的第一个记录做基准
index = a[i];
// 从表的两端交替向中间扫描
while (i < j) {
//先从高位向低位扫描
while (i < j && a[j] >= index)
j--;
if (i < j)
//用比基准小的记录替换低位记录
a[i++] = a[j];
//再从低位向高位扫描
while (i < j && a[i] < index)
i++;
if (i < j)
// 用比基准大的记录替换高位记录
a[j--] = a[i];
}
// 将基准数值替换回 a[i]
a[i] = index;
//继续分区
sort(a, low, i - 1); // 对低子表进行递归排序
sort(a, i + 1, hight); // 对高子表进行递归排序

}

public static void quickSort(int a[]) {
sort(a, 0, a.length - 1);
}

public static void main(String[] args) {

int a[] = { 48, 38, 69, 97, 76, 13, 37, 48 };
quickSort(a);
System.out.println(Arrays.toString(a));

}
}