排序算法的成本模型计算的是比较和交换的次数。好的排序算法应该尽量避免元素的交换。

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
/**
* 交换
*/
public static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}

private void exch(int i, int j) {
Key t = pq[i];
pq[i] = pq[j];
pq[j] = t;
}

/**
* 比较
*/
public static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}

private boolean less(int i, int j) {
return pq[i].compareTo(pq[j]) < 0;
}