基础排序

Elementary Sorts

获益良多,对 ∼N2\sim N^2 的基础排序算法 (插排,希尔排序) 有了新的认识。之前一直觉得有快排就够了 (N 方的排序算法是什么臭鱼烂虾),学完之后才发现这样的想法是多么傲慢。这些算法里蕴含的排序思想,和无数计算机科学家 (包括教授 Sedgewick) 尝试改进优化所做的努力,都是难能可贵的。

排序算法在 Java 中的实现离不开 Comparable 接口。有关这部分的内容 (包括下文所用到的 less 与 exch 辅助方法) 在 Java 配套笔记中进行记录。

Selection Sort

In iteration ii, find index minmin of smallest remaining entry. Then swap aia_i and amina_{min}.

JAva
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 0+1+...+(N−1)∼N2/20+1+...+(N-1)\sim N^2/2 compares and NN exchanges.

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 ii, swap aia_i with each larger entry to its left.

java
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 N−1N-1 compares and 00 exchanges.
  • Worst case. descending arrays: it makes ∼12N2\sim \frac{1}{2}N^2 compares and ∼12N2\sim \frac{1}{2}N^2 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 == exchanges +(N−1)+(N-1).

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 ≤cN\leq cN.

Shellsort

Idea. Move entries more than one position at a time by hh-sorting the array.

an -sorted array is  interleaved sorted subsequences

Shellsort. [Shell 1959] Repeatedly hh-sort the array with a decreasing sequence of values of hh.

We use insertion sort with stride length hh to hh-sort an array. why choosing insertion sort:

  • Big increments →\to small subarray.
  • Small increments →\to nearly in order. (insertion sort is fast when array is partially sorted)

Note the fact that a gg-sorted array remains gg-sorted after hh-sorting it.

An efficient shellsort scheme depends on a proper increment sequence.

  • 3x+13x+1. (most commonly used) 1,4,13,40,121,364,...1,4,13,40,121,364,...
  • Sedgewick. (tough to beat in empirical studies) 1,5,19,41,109,...1,5,19,41,109,...

The worst-case number of compares used by shellsort with the 3x+13x+1 increments is O(N3/2)O(N^{3/2}).

However, accurate model for shellsort has NOT yet been discovered. Maybe some better increment sequences are still left for discover......!

java
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 hh-sort the array, it is NOT stable.

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.

CC BY-NC-SA 4.0
正在加载评论…