基础排序
Elementary Sorts
获益良多,对 N 方的排序算法是什么臭鱼烂虾),学完之后才发现这样的想法是多么傲慢。这些算法里蕴含的排序思想,和无数计算机科学家 (包括教授 Sedgewick) 尝试改进优化所做的努力,都是难能可贵的。
排序算法在 Java 中的实现离不开 Comparable 接口。有关这部分的内容 (包括下文所用到的 less 与 exch 辅助方法) 在 Java 配套笔记中进行记录。
Selection Sort
In iteration
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 0; i < N; ++i) {
int min = i;
for (int j = i + 1; j < N; ++j)
if (less(a[j], a[min]))
min = j;
exch(a, i, min);
}
}
Proposition. Selection sort uses
The running time is intensive to input: it takes quadratic time even if input is sorted.
Knuth's shuffle is structurally similar to selection sort. It is used to generate random shuffles.
Insertion Sort
In iteration
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 0; i < N; ++i)
for (int j = i; j > 0; --j) {
if (less(a[j], a[j - 1]))
exch(a, j, j - 1);
else break;
}
}
Insertion sort is NOT intensive to input.
- Best case. ascending arrays: it makes
compares and exchanges. - Worst case. descending arrays: it makes
compares and exchanges.
Note that for partially-sorted arrays, insertion sort runs in linear time.
This is because number of exchanges equals the number of inversions, and numbers of compares
Def 1. An inversion is a pair of keys that are out of order.
Def 2. An array is partially sorted if the number of inversions is
Shellsort
Idea. Move entries more than one position at a time by
Shellsort. [Shell 1959] Repeatedly
We use insertion sort with stride length
- Big increments
small subarray. - Small increments
nearly in order. (insertion sort is fast when array is partially sorted)
Note the fact that a
An efficient shellsort scheme depends on a proper increment sequence.
. (most commonly used) - Sedgewick. (tough to beat in empirical studies)
The worst-case number of compares used by shellsort with the
However, accurate model for shellsort has NOT yet been discovered. Maybe some better increment sequences are still left for discover......!
public class Shell {
public static void sort(Comparable[] a) {
int N = a.length;
int h = 1;
while (h < N/3) h = 3 * h + 1; // generate 3x+1 increment sequence
while (h >= 1) { // h-insertion sort
for (int i = h; i < N; ++i) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h /= 3;
}
}
}
Also note that though shellsort uses insertion sort to
A stable sort preserves the relative order of items with equal keys.
Insertion sort and merge sort are stable; Selection sort and shellsort are not.
