CS-Notes/notes/算法.md

1783 lines
62 KiB
Markdown
Raw Normal View History

2018-06-04 14:28:30 +08:00
# 一、算法分析
## 数学模型
### 1. 近似
N<sup>3</sup>/6-N<sup>2</sup>/2+N/3 ~ N<sup>3</sup>/6。使用 ~f(N) 来表示所有随着 N 的增大除以 f(N) 的结果趋近于 1 的函数。
### 2. 增长数量级
N<sup>3</sup>/6-N<sup>2</sup>/2+N/3 的增长数量级为 O(N<sup>3</sup>)。增长数量级将算法与它的实现隔离开来一个算法的增长数量级为 O(N<sup>3</sup>) 与它是否用 Java 实现是否运行于特定计算机上无关。
### 3. 内循环
2018-04-06 22:46:59 +08:00
执行最频繁的指令决定了程序执行的总时间,把这些指令称为程序的内循环。
2018-06-04 14:28:30 +08:00
### 4. 成本模型
2018-04-06 22:46:59 +08:00
使用成本模型来评估算法,例如数组的访问次数就是一种成本模型。
2018-06-04 14:28:30 +08:00
## ThreeSum
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
ThreeSum 用于统计一个数组中和为 0 的三元组数量。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class ThreeSum {
    public static int count(int[] nums) {
        int N = nums.length;
        int cnt = 0;
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++)
                for (int k = j + 1; k < N; k++)
                    if (nums[i] + nums[j] + nums[k] == 0)
                        cnt++;
        return cnt;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
该算法的内循环为 `if (nums[i] + nums[j] + nums[k] == 0)` 语句总共执行的次数为 N(N-1)(N-2) = N<sup>3</sup>/6-N<sup>2</sup>/2+N/3因此它的近似执行次数为 ~N<sup>3</sup>/6增长数量级为 O(N<sup>3</sup>)。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<font size=4>**改进**</font></br>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
通过将数组先排序对两个元素求和并用二分查找方法查找是否存在该和的相反数如果存在就说明存在三元组的和为 0。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
该方法可以将 ThreeSum 算法增长数量级降低为 O(N<sup>2</sup>logN)。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class ThreeSumFast {
    public static int count(int[] nums) {
        Arrays.sort(nums);
        int N = nums.length;
        int cnt = 0;
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++) {
                int target = -nums[i] - nums[j];
                int index = binarySearch(nums, target);
                // 应该注意这里的下标必须大于 j否则会重复统计。
                if (index <= j)
                    continue;
                while (index < N && nums[index++] == target)
                    cnt++;
            }
        return cnt;
    }
    private static int binarySearch(int[] nums, int target) {
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (target == nums[m])
                return m;
            else if (target > nums[m])
                l = m + 1;
            else
                h = m - 1;
        }
        return -1;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 倍率实验
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
如果 T(N) ~ aN<sup>b</sup>logN那么 T(2N)/T(N) ~ 2<sup>b</sup>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
例如对于暴力的 ThreeSum 算法近似时间为 ~N<sup>3</sup>/6。进行如下实验多次运行该算法每次取的 N 值为前一次的两倍统计每次执行的时间并统计本次运行时间与前一次运行时间的比值得到如下结果
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
| N | Time(ms) | Ratio |
| :---: | :---: | :---: |
| 500 | 48 | / |
| 1000 | 320 | 6.7 |
| 2000 | 555 | 1.7 |
| 4000 | 4105 | 7.4 |
| 8000 | 33575 | 8.2 |
| 16000 | 268909 | 8.0 |
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
可以看到T(2N)/T(N) ~ 2<sup>3</sup>因此可以确定 T(N) ~ aN<sup>3</sup>logN。
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public class RatioTest {
    public static void main(String[] args) {
        int N = 500;
        int K = 7;
        long preTime = -1;
        while (K-- > 0) {
            int[] nums = new int[N];
            long startTime = System.currentTimeMillis();
            int cnt = ThreeSum.count(nums);
            long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            double ratio = preTime == -1 ? 0 : (double) time / preTime;
            System.out.println(N + "  " + time + "  " + ratio);
            preTime = time;
            N *= 2;
        }
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 注意事项
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 大常数
2018-04-06 22:46:59 +08:00
在求近似时,如果低级项的常数系数很大,那么近似的结果就是错误的。
2018-06-04 14:28:30 +08:00
### 2. 缓存
2018-04-06 22:46:59 +08:00
计算机系统会使用缓存技术来组织内存,访问数组相邻的元素会比访问不相邻的元素快很多。
2018-06-04 14:28:30 +08:00
### 3. 对最坏情况下的性能的保证
2018-04-06 22:46:59 +08:00
在核反应堆、心脏起搏器或者刹车控制器中的软件,最坏情况下的性能是十分重要的。
2018-06-04 14:28:30 +08:00
### 4. 随机化算法
2018-04-06 22:46:59 +08:00
通过打乱输入,去除算法对输入的依赖。
2018-06-04 14:28:30 +08:00
### 5. 均摊分析
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
将所有操作的总成本除于操作总数来将成本均摊。例如对一个空栈进行 N 次连续的 push() 调用需要访问数组的元素为 N+4+8+16+...+2N=5N-4N 是向数组写入元素其余的都是调整数组大小时进行复制需要的访问数组操作均摊后每次操作访问数组的平均次数为常数。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
# 二、栈和队列
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 栈
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
First-In-Last-Out
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 数组实现
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
import java.util.Iterator;
public class ResizingArrayStack<Item> implements Iterable<Item> {
    // 栈元素数组
    private Item[] a = (Item[]) new Object[1]; // 只能通过转型来创建泛型数组
    // 元素数量
    private int N = 0;
    public void push(Item item) {
        check();
        a[N++] = item;
    }
    public Item pop() throws Exception {
        if (isEmpty())
            throw new Exception("stack is empty");
        Item item = a[--N];
        check();
        a[N] = null; // 避免对象游离
        return item;
    }
    private void check() {
        if (N >= a.length)
            resize(2 * a.length);
        else if (N > 0 && N <= a.length / 4)
            resize(a.length / 2);
    }
    /**
     * 调整数组大小,使得栈具有伸缩性
     */
    private void resize(int size) {
        Item[] tmp = (Item[]) new Object[size];
        for (int i = 0; i < N; i++)
            tmp[i] = a[i];
        a = tmp;
    }
    public boolean isEmpty() {
        return N == 0;
    }
    public int size() {
        return N;
    }
    @Override
    public Iterator<Item> iterator() {
        // 返回逆序遍历的迭代器
        return new ReverseArrayIterator();
    }
    private class ReverseArrayIterator implements Iterator<Item> {
        private int i = N;
        @Override
        public boolean hasNext() {
            return i > 0;
        }
        @Override
        public Item next() {
            return a[--i];
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public static void main(String[] args) throws Exception {
    ResizingArrayStack<Integer> stack = new ResizingArrayStack();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    System.out.println(stack.isEmpty());
    System.out.println(stack.size());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    for (Integer item : stack)
        System.out.println(item);
2018-05-09 17:15:36 +08:00
}
```
```html
false
4
4
3
2
1
```
2018-06-04 14:28:30 +08:00
### 2. 链表实现
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
需要使用链表的头插法来实现因为头插法中最后压入栈的元素在链表的开头它的 next 指针指向前一个压入栈的元素在弹出元素使就可以通过 next 指针遍历到前一个压入栈的元素从而让这个元素称为新的栈顶元素。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class ListStack<Item> {
    private Node top = null;
    private int N = 0;
    private class Node {
        Item item;
        Node next;
    }
    public boolean isEmpty() {
        return N == 0;
    }
    public int size() {
        return N;
    }
    public void push(Item item) {
        Node newTop = new Node();
        newTop.item = item;
        newTop.next = top;
        top = newTop;
        N++;
    }
    public Item pop() throws Exception {
        if (isEmpty())
            throw new Exception("stack is empty");
        Item item = top.item;
        top = top.next;
        N--;
        return item;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public static void main(String[] args) throws Exception {
    ListStack<Integer> stack = new ListStack();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    System.out.println(stack.isEmpty());
    System.out.println(stack.size());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
2018-05-09 17:15:36 +08:00
}
```
```html
false
4
4
3
```
2018-06-04 14:28:30 +08:00
## 队列
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
First-In-First-Out
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
下面是队列的链表实现需要维护 first  last 节点指针分别指向队首和队尾。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
这里需要考虑 first  last 指针哪个作为链表的开头。因为出队列操作需要让队首元素的下一个元素成为队首所以需要容易获取下一个元素而链表的头部节点的 next 指针指向下一个元素因此可以让 first 指针链表的开头。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Queue<Item> {
    private Node first;
    private Node last;
    int N = 0;
    private class Node {
        Item item;
        Node next;
    }
    public boolean isEmpty() {
        return N == 0;
    }
    public int size() {
        return N;
    }
    public void add(Item item) {
        Node newNode = new Node();
        newNode.item = item;
        newNode.next = null;
        if (isEmpty()) {
            last = newNode;
            first = newNode;
        } else {
            last.next = newNode;
            last = newNode;
        }
        N++;
    }
    public Item remove() throws Exception {
        if (isEmpty())
            throw new Exception("queue is empty");
        Node node = first;
        first = first.next;
        N--;
        if (isEmpty())
            last = null;
        return node.item;
    }
2018-04-06 22:46:59 +08:00
}
```
```java
2018-06-04 14:28:30 +08:00
public static void main(String[] args) throws Exception {
    Queue queue = new Queue();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.remove());
    System.out.println(queue.remove());
    queue.add(3);
    queue.add(4);
    System.out.println(queue.size());
2018-04-06 22:46:59 +08:00
}
```
2018-05-09 17:15:36 +08:00
```html
1
2
2
2018-04-06 22:46:59 +08:00
```
2018-06-04 14:28:30 +08:00
# 三、排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
待排序的元素需要实现 Java  Comparable 接口该接口有 compareTo() 方法,可以用它来判断两个元素的大小关系。
2018-04-06 22:46:59 +08:00
研究排序算法的成本模型时,计算的是比较和交换的次数。
2018-06-04 14:28:30 +08:00
使用辅助函数 less()  swap() 来进行比较和交换的操作,使得代码的可读性和可移植性更好。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private static boolean less(Comparable v, Comparable w) {
    return v.compareTo(w) < 0;
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private static void swap(Comparable[] a, int i, int j) {
    Comparable t = a[i];
    a[i] = a[j];
    a[j] = t;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 选择排序
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
选择出数组中的最小元素,将它与数组的第一个元素交换位置。再从剩下的元素中选择出最小的元素,将它与数组的第二个元素交换位置。不断进行这样的操作,直到将整个数组排序。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/ed7b96ac-6428-4bd5-9986-674c54c2a959.png" width="250"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Selection {
    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;
            swap(a, i, min);
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
选择排序需要 ~N<sup>2</sup>/2 次比较和 ~N 次交换它的运行时间与输入无关这个特点使得它对一个已经排序的数组也需要这么多的比较和交换操作。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 冒泡排序
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
通过从左到右不断交换相邻逆序的相邻元素,在一轮的交换之后,可以让未排序的元素上浮到最右侧,是的右侧是已排序的。
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
在一轮交换中,如果没有发生交换,就说明数组已经是有序的,此时可以直接退出。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Bubble {
    public static void sort(Comparable[] a) {
        int N = a.length;
        boolean hasSorted = false;
        for (int i = 0; i < N && !hasSorted; i++) {
            hasSorted = true;
            for (int j = 0; j < N - i - 1; j++) {
                if (less(a[j + 1], a[j])) {
                    hasSorted = false;
                    swap(a, j, j + 1);
                }
            }
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 插入排序
2018-05-09 17:15:36 +08:00
插入排序从左到右进行,每次都将当前元素插入到左侧已经排序的数组中,使得插入之后左部数组依然有序。
2018-06-04 14:28:30 +08:00
 j 元素是通过不断向左比较并交换来实现插入过程当第 j 元素小于第 j - 1 元素就将它们的位置交换然后令 j 指针向左移动一个位置不断进行以上操作。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/c9a1de44-b1c0-4d13-a654-827d4ef8a723.png" width="250"/>
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Insertion {
    public static void sort(Comparable[] a) {
        int N = a.length;
        for (int i = 1; i < N; i++)
            for (int j = i; j > 0 && less(a[j], a[j - 1]); j--)
                swap(a, j, j - 1);
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
对于数组 {3, 5, 2, 4, 1},它具有以下逆序:(3, 2), (3, 1), (5, 2), (5, 4), (5, 1), (2, 1), (4, 1)插入排序每次只能交换相邻元素令逆序数量减少 1因此插入排序需要交换的次数为逆序数量。
2018-05-09 17:15:36 +08:00
插入排序的复杂度取决于数组的初始顺序,如果数组已经部分有序了,逆序较少,那么插入排序会很快。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- 平均情况下插入排序需要 ~N<sup>2</sup>/4 比较以及 ~N<sup>2</sup>/4 次交换
- 最坏的情况下需要 ~N<sup>2</sup>/2 比较以及 ~N<sup>2</sup>/2 次交换最坏的情况是数组是倒序的
- 最好的情况下需要 N-1 次比较和 0 次交换最好的情况就是数组已经有序了。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 希尔排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
对于大规模的数组插入排序很慢因为它只能交换相邻的元素每次只能将逆序数量减少 1。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
希尔排序的出现就是为了改进插入排序的这种局限性它通过交换不相邻的元素每次可以将逆序数量减少大于 1。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
希尔排序使用插入排序对间隔 h 的序列进行排序。通过不断减小 h最后令 h=1就可以使得整个数组是有序的。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/cdbe1d12-5ad9-4acb-a717-bbc822c2acf3.png" width="500"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Shell {
    public static void sort(Comparable[] a) {
        int N = a.length;
        int h = 1;
        while (h < N / 3)
            h = 3 * h + 1; // 1, 4, 13, 40, ...
        while (h >= 1) {
            for (int i = h; i < N; i++)
                for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
                    swap(a, j, j - h);
            h = h / 3;
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
希尔排序的运行时间达不到平方级别使用递增序列 1, 4, 13, 40, ...  的希尔排序所需要的比较次数不会超过 N 的若干倍乘于递增序列的长度。后面介绍的高级排序算法只会比希尔排序快两倍左右。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 归并排序
2018-04-06 22:46:59 +08:00
归并排序的思想是将数组分成两部分,分别进行排序,然后归并起来。
2018-06-04 14:28:30 +08:00
<img src="index_files/8dfb4cc9-26da-45e7-b820-4576fa1cbb0e.png" width="350"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 归并方法
2018-04-06 22:46:59 +08:00
归并方法将数组中两个已经排序的部分归并成一个。
```java
2018-06-04 14:28:30 +08:00
public class MergeSort {
    private static Comparable[] aux;
    private static void merge(Comparable[] a, int l, int m, int h) {
        int i = l, j = m + 1;
        for (int k = l; k <= h; k++)
            aux[k] = a[k]; // 将数据复制到辅助数组
        for (int k = l; k <= h; k++) {
            if (i > m)
                a[k] = aux[j++];
            else if (j > h)
                a[k] = aux[i++];
            else if (aux[i].compareTo(a[j]) <= 0)
                a[k] = aux[i++]; // 先进行这一步,保证稳定性
            else
                a[k] = aux[j++];
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. 自顶向下归并排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/0c55e11c-d3ce-4cd8-b139-028aea6f40e3.png" width="450"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public static void sort(Comparable[] a) {
    aux = new Comparable[a.length];
    sort(a, 0, a.length - 1);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private static void sort(Comparable[] a, int l, int h) {
    if (h <= l)
        return;
    int mid = l + (h - l) / 2;
    sort(a, l, mid);
    sort(a, mid + 1, h);
    merge(a, l, mid, h);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
因为每次都将问题对半分成两个子问题而这种对半分的算法复杂度一般为 O(NlogN)因此该归并排序方法的时间复杂度也为 O(NlogN)。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 3. 自底向上归并排序
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
先归并那些微型数组,然后成对归并得到的微型数组。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
 public static void sort(Comparable[] a) {
     int N = a.length;
     aux = new Comparable[N];
     for (int sz = 1; sz < N; sz += sz) {
         for (int lo = 0; lo < N - sz; lo += sz + sz) {
             merge(a, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, N - 1));
         }
     }
 }
2018-04-06 22:46:59 +08:00
```
2018-06-04 14:28:30 +08:00
## 快速排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 基本算法
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- 归并排序将数组分为两个子数组分别排序,并将有序的子数组归并使得整个数组排序;
- 快速排序通过一个切分元素将数组分为两个子数组,左子数组小于等于切分元素,右子数组大于等于切分元素,将这两个子数组排序也就将整个数组排序了。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/ab77240d-7338-4547-9183-00215e7220ec.png" width="500"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class QuickSort {
    public static void sort(Comparable[] a) {
        shuffle(a);
        sort(a, 0, a.length - 1);
    }
    private static void sort(Comparable[] a, int l, int h) {
        if (h <= l)
            return;
        int j = partition(a, l, h);
        sort(a, l, j - 1);
        sort(a, j + 1, h);
    }
    private static void shuffle(Comparable[] array) {
        List<Comparable> list = Arrays.asList(array);
        Collections.shuffle(list);
        list.toArray(array);
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. 切分
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
 a[lo] 作为切分元素然后从数组的左端向右扫描直到找到第一个大于等于它的元素再从数组的右端向左扫描找到第一个小于等于它的元素交换这两个元素并不断进行这个过程就可以保证左指针 i 的左侧元素都不大于切分元素右指针 j 的右侧元素都不小于切分元素。当两个指针相遇时将切分元素 a[lo]  a[j] 交换位置。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/5aac64d3-2c7b-4f32-9e9a-1df2186f588b.png" width="300"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private static int partition(Comparable[] a, int l, int h) {
    int i = l, j = h + 1;
    Comparable v = a[l];
    while (true) {
        while (less(a[++i], v) && i != h) ;
        while (less(v, a[--j]) && j != l) ;
        if (i >= j)
            break;
        swap(a, i, j);
    }
    swap(a, l, j);
    return j;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 3. 性能分析
2018-04-06 22:46:59 +08:00
快速排序是原地排序,不需要辅助数组,但是递归调用需要辅助栈。
2018-06-04 14:28:30 +08:00
快速排序最好的情况下是每次都正好能将数组对半分这样递归调用次数才是最少的。这种情况下比较次数为 C<sub>N</sub>=2C<sub>N/2</sub>+N复杂度为 O(NlogN)。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
最坏的情况下第一次从最小的元素切分第二次从第二小的元素切分如此这般。因此最坏的情况下需要比较 N<sup>2</sup>/2。为了防止数组最开始就是有序的在进行快速排序时需要随机打乱数组。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 4. 算法改进
2018-04-06 22:46:59 +08:00
(一)切换到插入排序
2018-05-09 17:15:36 +08:00
因为快速排序在小数组中也会递归调用自己,对于小数组,插入排序比快速排序的性能更好,因此在小数组中可以切换到插入排序。
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
(二)三数取中
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
最好的情况下是每次都能取数组的中位数作为切分元素但是计算中位数的代价很高。人们发现取 3 个元素并将大小居中的元素作为切分元素的效果最好。
2018-04-06 22:46:59 +08:00
(三)三向切分
对于有大量重复元素的数组,可以将数组切分为三部分,分别对应小于、等于和大于切分元素。
三向切分快速排序对于只有若干不同主键的随机数组可以在线性时间内完成排序。
```java
2018-06-04 14:28:30 +08:00
public class Quick3Way {
    public static void sort(Comparable[] a) {
        sort(a, 0, a.length - 1);
    }
    private static void sort(Comparable[] a, int l, int h) {
        if (h <= l)
            return;
        int lt = l, i = l + 1, gt = h;
        Comparable v = a[l];
        while (i <= gt) {
            int cmp = a[i].compareTo(v);
            if (cmp < 0)
                swap(a, lt++, i++);
            else if (cmp > 0)
                swap(a, i, gt--);
            else
                i++;
        }
        sort(a, l, lt - 1);
        sort(a, gt + 1, h);
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 5. 基于切分的快速选择算法
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
快速排序的 partition() 方法会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j] a[j+1..h] 大于等于 a[j]此时 a[j] 就是数组的第 j 大元素。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
可以利用这个特性找出数组的第 k 个元素。
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public static Comparable select(Comparable[] a, int k) {
    int l = 0, h = a.length - 1;
    while (h > l) {
        int j = partition(a, l, h);
        if (j == k)
            return a[k];
        else if (j > k)
            h = j - 1;
        else
            l = j + 1;
    }
    return a[k];
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
该算法是线性级别的,因为每次正好将数组二分,那么比较的总次数为 (N+N/2+N/4+..)直到找到第 k 个元素这个和显然小于 2N。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 堆排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 堆
2018-04-06 22:46:59 +08:00
堆的某个节点的值总是大于等于子节点的值,并且堆是一颗完全二叉树。
2018-06-04 14:28:30 +08:00
堆可以用数组来表示因为堆是一种完全二叉树而完全二叉树很容易就存储在数组中。位置 k 的节点的父节点位置为 k/2而它的两个子节点的位置分别为 2k  2k+1。这里不使用数组索引为 0 的位置是为了更清晰地描述节点的位置关系。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/f3080f83-6239-459b-8e9c-03b6641f7815.png" width="200"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Heap {
    private Comparable[] heap;
    private int N = 0;
    public Heap(int maxN) {
        heap = new Comparable[maxN + 1];
        N = maxN;
    }
    public boolean isEmpty() {
        return N == 0;
    }
    public int size() {
        return N;
    }
    private boolean less(int i, int j) {
        return heap[i].compareTo(heap[j]) < 0;
    }
    private void swap(int i, int j) {
        Comparable t = heap[i];
        heap[i] = heap[j];
        heap[j] = t;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. 上浮和下沉
2018-04-06 22:46:59 +08:00
2018-05-09 17:15:36 +08:00
在堆中,当一个节点比父节点大,那么需要交换这个两个节点。交换后还可能比它新的父节点大,因此需要不断地进行比较和交换操作,把这种操作称为上浮。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/33ac2b23-cb85-4e99-bc41-b7b7199fad1c.png" width="400"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private void swim(int k) {
    while (k > 1 && less(k / 2, k)) {
        swap(k / 2, k);
        k = k / 2;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-05-09 17:15:36 +08:00
类似地,当一个节点比子节点来得小,也需要不断地向下进行比较和交换操作,把这种操作称为下沉。一个节点有两个子节点,应当与两个子节点中最大那么节点进行交换。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/72f0ff69-138d-4e54-b7ac-ebe025d978dc.png" width="400"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private void sink(int k) {
    while (2 * k <= N) {
        int j = 2 * k;
        if (j < N && less(j, j + 1))
            j++;
        if (!less(k, j))
            break;
        swap(k, j);
        k = j;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 3. 插入元素
2018-04-06 22:46:59 +08:00
将新元素放到数组末尾,然后上浮到合适的位置。
```java
2018-06-04 14:28:30 +08:00
public void insert(Comparable v) {
    heap[++N] = v;
    swim(N);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 4. 删除最大元素
2018-04-06 22:46:59 +08:00
从数组顶端删除最大的元素,并将数组的最后一个元素放到顶端,并让这个元素下沉到合适的位置。
```java
2018-06-04 14:28:30 +08:00
public Comparable delMax() {
    Comparable max = heap[1];
    swap(1, N--);
    heap[N + 1] = null;
    sink(1);
    return max;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 5. 堆排序
2018-04-06 22:46:59 +08:00
由于堆可以很容易得到最大的元素并删除它,不断地进行这种操作可以得到一个递减序列。如果把最大元素和当前堆中数组的最后一个元素交换位置,并且不删除它,那么就可以得到一个从尾到头的递减序列,从正向来看就是一个递增序列。因此很容易使用堆来进行排序,并且堆排序是原地排序,不占用额外空间。
(一)构建堆
无序数组建立堆最直接的方法是从左到右遍历数组,然后进行上浮操作。一个更高效的方法是从右至左进行下沉操作,如果一个节点的两个节点都已经是堆有序,那么进行下沉操作可以使得这个节点为根节点的堆有序。叶子节点不需要进行下沉操作,因此可以忽略叶子节点的元素,因此只需要遍历一半的元素即可。
2018-06-04 14:28:30 +08:00
<img src="index_files/b84ba6fb-312b-4e69-8c77-fb6eb6fb38d4.png" width="300"/>
2018-04-06 22:46:59 +08:00
(二)交换堆顶元素与最后一个元素
交换之后需要进行下沉操作维持堆的有序状态。
2018-06-04 14:28:30 +08:00
<img src="index_files/51fb761d-8ce0-4472-92ff-2f227ac7888a.png" width="270"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/1f039a45-6b91-4f31-a2c2-6c63eb8bdb56.png" width="300"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class HeapSort {
    public static void sort(Comparable[] a) { // 数组第 0 个位置不能有元素
        int N = a.length - 1;
        for (int k = N / 2; k >= 0; k--)
            sink(a, k, N);
        while (N > 1) {
            swap(a, 1, N--);
            sink(a, 1, N);
        }
    }
    private static void sink(Comparable[] a, int k, int N) {
        while (2 * k <= N) {
            int j = 2 * k;
            if (j < N && less(a, j, j + 1))
                j++;
            if (!less(a, k, j))
                break;
            swap(a, k, j);
            k = j;
        }
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 6. 分析
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
一个堆的高度为 logN因此在堆中插入元素和删除最大元素的复杂度都为 logN。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
对于堆排序由于要对 N 个节点进行下沉操作因此复杂度为 NlogN。
2018-04-06 22:46:59 +08:00
堆排序时一种原地排序,没有利用额外的空间。
现代操作系统很少使用堆排序,因为它无法利用缓存,也就是数组元素很少和相邻的元素进行比较。
2018-06-04 14:28:30 +08:00
## 桶排序
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
## 基数排序
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
## 外部排序
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 排序算法的比较
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
| 算法 | 稳定 | 原地排序 | 时间复杂度 | 空间复杂度 | 备注 |
| :---: | :---: | :---: | :---: | :---: | :---: |
| 选择排序 | no | yes | N<sup>2</sup> | 1 | |
| 插入排序 | yes | yes | N ~ N<sup>2</sup> | 1 | 时间复杂度和初始顺序有关 |
| 希尔排序 | no | yes | N 的若干倍乘于递增序列的长度 | 1 | |
| 快速排序 | no | yes | NlogN | logN | |
| 三向切分快速排序 | no | yes | N ~ NlogN | logN | 适用于有大量重复主键|
| 归并排序 | yes | no | NlogN | N | |
| 堆排序 | no | yes | NlogN | 1 | | |
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
快速排序是最快的通用排序算法,它的内循环的指令很少,而且它还能利用缓存,因为它总是顺序地访问数据。它的运行时间近似为 ~cNlogN这里的 c 比其他线性对数级别的排序算法都要小。使用三向切分快速排序实际应用中可能出现的某些分布的输入能够达到线性级别而其它排序算法仍然需要线性对数时间。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## Java 的排序算法实现
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
Java 主要排序方法为 java.util.Arrays.sort(),对于原始数据类型使用三向切分的快速排序,对于引用类型使用归并排序。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
# 四、查找
2018-04-06 22:46:59 +08:00
符号表是一种存储键值对的数据结构,主要支持两种操作:插入一个新的键值对、根据给定键得到值。
2018-06-04 14:28:30 +08:00
符号表分为有序和无序两种有序符号表主要指支持 min()、max() 等根据键的大小关系来实现的操作。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
有序符号表的键需要实现 Comparable 接口。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 二分查找实现有序符号表
2018-04-06 22:46:59 +08:00
使用一对平行数组,一个存储键一个存储值。
2018-06-04 14:28:30 +08:00
rank() 方法至关重要,当键在表中时,它能够知道该键的位置;当键不在表中时,它也能知道在何处插入新键。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
复杂度二分查找最多需要 logN+1 次比较使用二分查找实现的符号表的查找操作所需要的时间最多是对数级别的。但是插入操作需要移动数组元素是线性级别的。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private Key[] keys;
    private Value[] values;
    private int N;
    public BinarySearchST(int capacity) {
        keys = (Key[]) new Comparable[capacity];
        values = (Value[]) new Object[capacity];
    }
    public int size() {
        return N;
    }
    public Value get(Key key) {
        int i = rank(key);
        if (i < N && keys[i].compareTo(key) == 0) {
            return values[i];
        }
        return null;
    }
    public int rank(Key key) {
        int lo = 0, hi = N - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int cmp = key.compareTo(keys[mid]);
            if (cmp == 0) return mid;
            else if (cmp < 0) hi = mid - 1;
            else lo = mid + 1;
        }
        return lo;
    }
    public void put(Key key, Value value) {
        int i = rank(key);
        if (i < N && keys[i].compareTo(key) == 0) {
            values[i] = value;
            return;
        }
        for (int j = N; j > i; j--) {
            keys[j] = keys[j - 1];
            values[j] = values[j - 1];
        }
        keys[i] = key;
        values[i] = value;
        N++;
    }
    public Key ceiling(Key key){
        int i = rank(key);
        return keys[i];
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 二叉查找树
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
**二叉树** 是一个空链接,或者是一个有左右两个链接的节点,每个链接都指向一颗子二叉树。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/f9f9f993-8ece-4da7-b848-af9b438fad76.png" width="200"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
**二叉查找树**BST是一颗二叉树并且每个节点的值都大于等于其左子树中的所有节点的值而小于等于右子树的所有节点的值。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/8ae4550b-f0cb-4e4d-9e2b-c550538bf230.png" width="200"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
BST 有一个重要性质就是它的中序遍历结果递增排序。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/fbe54203-c005-48f0-8883-b05e564a3173.png" width="200"/>
2018-04-06 22:46:59 +08:00
基本数据结构:
```java
2018-06-04 14:28:30 +08:00
public class BST<Key extends Comparable<Key>, Value> {
    private Node root;
    private class Node {
        private Key key;
        private Value val;
        private Node left, right;
        // 以该节点为根的子树中节点总数
        private int N;
        public Node(Key key, Value val, int N) {
            this.key = key;
            this.val = val;
            this.N = N;
        }
    }
    public int size() {
        return size(root);
    }
    private int size(Node x) {
        if (x == null) return 0;
        return x.N;
    }
2018-04-06 22:46:59 +08:00
}
```
(为了方便绘图,二叉树的空链接不画出来。)
2018-06-04 14:28:30 +08:00
### 1. get()
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- 如果树是空的,则查找未命中;
- 如果被查找的键和根节点的键相等,查找命中;
- 否则递归地在子树中查找:如果被查找的键较小就在左子树中查找,较大就在右子树中查找。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public Value get(Key key) {
    return get(root, key);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private Value get(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return x.val;
    else if (cmp < 0) return get(x.left, key);
    else return get(x.right, key);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. put()
2018-04-06 22:46:59 +08:00
当插入的键不存在于树中,需要创建一个新节点,并且更新上层节点的链接使得该节点正确链接到树中。
2018-06-04 14:28:30 +08:00
<img src="index_files/107a6a2b-f15b-4cad-bced-b7fb95258c9c.png" width="200"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public void put(Key key, Value val) {
    root = put(root, key, val);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private Node put(Node x, Key key, Value val) {
    if (x == null) return new Node(key, val, 1);
    int cmp = key.compareTo(x.key);
    if (cmp == 0) x.val = val;
    else if (cmp < 0) x.left = put(x.left, key, val);
    else x.right = put(x.right, key, val);
    x.N = size(x.left) + size(x.right) + 1;
    return x;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 3. 分析
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
二叉查找树的算法运行时间取决于树的形状而树的形状又取决于键被插入的先后顺序。最好的情况下树是完全平衡的每条空链接和根节点的距离都为 logN。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/4d741402-344d-4b7c-be01-e57184bcad0e.png" width="200"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
在最坏的情况下树的高度为 N。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/be7dca03-12ec-456b-8b54-b1b3161f5531.png" width="200"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 4. floor()
2018-04-06 22:46:59 +08:00
floor(key):小于等于键的最大键
2018-06-04 14:28:30 +08:00
- 如果键小于根节点的键那么 floor(key) 一定在左子树中;
- 如果键大于根节点的键需要先判断右子树中是否存在 floor(key)如果存在就找到否则根节点就是 floor(key)。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public Key floor(Key key) {
    Node x = floor(root, key);
    if (x == null) return null;
    return x.key;
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private Node floor(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return x;
    if (cmp < 0) return floor(x.left, key);
    Node t = floor(x.right, key);
    if (t != null) {
        return t;
    } else {
        return x;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 5. rank()
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
rank(key) 返回 key 的排名。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- 如果键和根节点的键相等,返回左子树的节点数;
- 如果小于,递归计算在左子树中的排名;
- 如果大于递归计算在右子树中的排名并加上左子树的节点数再加上 1根节点
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public int rank(Key key) {
    return rank(key, root);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private int rank(Key key, Node x) {
    if (x == null) return 0;
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return size(x.left);
    else if (cmp < 0) return rank(key, x.left);
    else return 1 + size(x.left) + rank(key, x.right);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 6. min()
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private Node min(Node x) {
    if (x == null) return null;
    if (x.left == null) return x;
    return min(x.left);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 7. deleteMin()
2018-04-06 22:46:59 +08:00
令指向最小节点的链接指向最小节点的右子树。
2018-06-04 14:28:30 +08:00
<img src="index_files/dd15a984-e977-4644-b127-708cddb8ca99.png" width="500"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public void deleteMin() {
    root = deleteMin(root);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
public Node deleteMin(Node x) {
    if (x.left == null) return x.right;
    x.left = deleteMin(x.left);
    x.N = size(x.left) + size(x.right) + 1;
    return x;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 8. delete()
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- 如果待删除的节点只有一个子树,那么只需要让指向待删除节点的链接指向唯一的子树即可;
- 否则,让右子树的最小节点替换该节点。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/fa568fac-ac58-48dd-a9bb-23b3065bf2dc.png" width="400"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public void delete(Key key) {
    root = delete(root, key);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private Node delete(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp < 0) x.left = delete(x.left, key);
    else if (cmp > 0) x.right = delete(x.right, key);
    else {
        if (x.right == null) return x.left;
        if (x.left == null) return x.right;
        Node t = x;
        x = min(t.right);
        x.right = deleteMin(t.right);
        x.left = t.left;
    }
    x.N = size(x.left) + size(x.right) + 1;
    return x;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 9. keys()
2018-04-06 22:46:59 +08:00
利用二叉查找树中序遍历的结果为递增的特点。
```java
2018-06-04 14:28:30 +08:00
public Iterable<Key> keys(Key lo, Key hi) {
    Queue<Key> queue = new LinkedList<>();
    keys(root, queue, lo, hi);
    return queue;
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
    if (x == null) return;
    int cmpLo = lo.compareTo(x.key);
    int cmpHi = hi.compareTo(x.key);
    if (cmpLo < 0) keys(x.left, queue, lo, hi);
    if (cmpLo <= 0 && cmpHi >= 0) queue.add(x.key);
    if (cmpHi > 0) keys(x.right, queue, lo, hi);
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 10. 性能分析
2018-04-06 22:46:59 +08:00
复杂度:二叉查找树所有操作在最坏的情况下所需要的时间都和树的高度成正比。
2018-06-04 14:28:30 +08:00
## 2-3 查找树
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/ff396233-1bb1-4e74-8bc2-d7c90146f5dd.png" width="250"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
2-3 查找树引入了 2- 节点和 3- 节点目的是为了让树平衡。一颗完美平衡的 2-3 查找树的所有空链接到根节点的距离应该是相同的。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 插入操作
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
插入操作和 BST 的插入操作有很大区别BST 的插入操作是先进行一次未命中的查找然后再将节点插入到对应的空链接上。但是 2-3 查找树如果也这么做的话那么就会破坏了平衡性。它是将新节点插入到叶子节点上。
2018-04-06 22:46:59 +08:00
根据叶子节点的类型不同,有不同的处理方式。
2018-06-04 14:28:30 +08:00
插入到 2- 节点上那么直接将新节点和原来的节点组成 3- 节点即可。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/7f38a583-2f2e-4738-97af-510e6fb403a7.png" width="400"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
如果是插入到 3- 节点上就会产生一个临时 4- 节点时需要将 4- 节点分裂成 3  2- 节点并将中间的 2- 节点移到上层节点中。如果上移操作继续产生临时 4- 节点则一直进行分裂上移直到不存在临时 4- 节点。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/ef280699-da36-4b38-9735-9b048a3c7fe0.png" width="500"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 2. 性质
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
2-3 查找树插入操作的变换都是局部的除了相关的节点和链接之外不必修改或者检查树的其它部分而这些局部变换不会影响树的全局有序性和平衡性。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
2-3 查找树的查找和插入操作复杂度和插入顺序无关在最坏的情况下查找和插入操作访问的节点必然不超过 logN 含有 10 亿个节点的 2-3 查找树最多只需要访问 30 个节点就能进行任意的查找和插入操作。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
## 红黑二叉查找树
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
2-3 查找树需要用到 2- 节点和 3- 节点红黑树使用红链接来实现 3- 节点。指向一个节点的链接颜色如果为红色那么这个节点和上层节点表示的是一个 3- 节点,而黑色则是普通链接。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/4f48e806-f90b-4c09-a55f-ac0cd641c047.png" width="250"/>
2018-04-06 22:46:59 +08:00
红黑树具有以下性质:
2018-06-04 14:28:30 +08:00
1. 红链接都为左链接;
2. 完美黑色平衡,即任意空链接到根节点的路径上的黑链接数量相同。
2018-04-06 22:46:59 +08:00
画红黑树时可以将红链接画平。
2018-06-04 14:28:30 +08:00
<img src="index_files/3086c248-b552-499e-b101-9cffe5c2773e.png" width="300"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class RedBlackBST<Key extends Comparable<Key>, Value> {
    private Node root;
    private static final boolean RED = true;
    private static final boolean BLACK = false;
    private class Node {
        Key key;
        Value val;
        Node left, right;
        int N;
        boolean color;
        Node(Key key, Value val, int n, boolean color) {
            this.key = key;
            this.val = val;
            N = n;
            this.color = color;
        }
    }
    private boolean isRed(Node x) {
        if (x == null) return false;
        return x.color == RED;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 1. 左旋转
2018-04-06 22:46:59 +08:00
因为合法的红链接都为左链接,如果出现右链接为红链接,那么就需要进行左旋转操作。
2018-06-04 14:28:30 +08:00
<img src="index_files/9110c1a0-8a54-4145-a814-2477d0128114.png" width="450"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public Node rotateLeft(Node h) {
    Node x = h.right;
    h.right = x.left;
    x.left = h;
    x.color = h.color;
    h.color = RED;
    x.N = h.N;
    h.N = 1 + size(h.left) + size(h.right);
    return x;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. 右旋转
2018-04-06 22:46:59 +08:00
进行右旋转是为了转换两个连续的左红链接,这会在之后的插入过程中探讨。
2018-06-04 14:28:30 +08:00
<img src="index_files/e2f0d889-2330-424c-8193-198edebecff7.png" width="450"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public Node rotateRight(Node h) {
    Node x = h.left;
    h.left = x.right;
    x.color = h.color;
    h.color = RED;
    x.N = h.N;
    h.N = 1 + size(h.left) + size(h.right);
    return x;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 3. 颜色转换
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
一个 4- 节点在红黑树中表现为一个节点的左右子节点都是红色的。分裂 4- 节点除了需要将子节点的颜色由红变黑之外同时需要将父节点的颜色由黑变红 2-3 树的角度看就是将中间节点移到上层节点。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/af4639f9-af54-4400-aaf5-4e261d96ace7.png" width="300"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
void flipColors(Node h){
    h.color = RED;
    h.left.color = BLACK;
    h.right.color = BLACK;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 4. 插入
2018-04-06 22:46:59 +08:00
先将一个节点按二叉查找树的方法插入到正确位置,然后再进行如下颜色操作:
2018-06-04 14:28:30 +08:00
- 如果右子节点是红色的而左子节点是黑色的,进行左旋转;
- 如果左子节点是红色的,而且左子节点的左子节点也是红色的,进行右旋转;
- 如果左右子节点均为红色的,进行颜色转换。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/08427d38-8df1-49a1-8990-e0ce5ee36ca2.png" width="400"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public void put(Key key, Value val) {
    root = put(root, key, val);
    root.color = BLACK;
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private Node put(Node x, Key key, Value val) {
    if (x == null) return new Node(key, val, 1, RED);
    int cmp = key.compareTo(x.key);
    if (cmp == 0) x.val = val;
    else if (cmp < 0) x.left = put(x.left, key, val);
    else x.right = put(x.right, key, val);
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
    if (isRed(x.right) && !isRed(x.left)) x = rotateLeft(x);
    if (isRed(x.left) && isRed(x.left.left)) x = rotateRight(x);
    if (isRed(x.left) && isRed(x.right)) flipColors(x);
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
    x.N = size(x.left) + size(x.right) + 1;
    return x;
2018-04-06 22:46:59 +08:00
}
```
可以看到该插入操作和二叉查找树的插入操作类似,只是在最后加入了旋转和颜色变换操作即可。
2018-06-04 14:28:30 +08:00
根节点一定为黑色因为根节点没有上层节点也就没有上层节点的左链接指向根节点。flipColors() 有可能会使得根节点的颜色变为红色每当根节点由红色变成黑色时树的黑链接高度加 1.
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 5. 分析
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
一颗大小为 N 的红黑树的高度不会超过 2logN。最坏的情况下是它所对应的 2-3 构成最左边的路径节点全部都是 3- 节点而其余都是 2- 节点。
2018-04-06 22:46:59 +08:00
红黑树大多数的操作所需要的时间都是对数级别的。
2018-06-04 14:28:30 +08:00
## 散列表
2018-04-06 22:46:59 +08:00
散列表类似于数组,可以把散列表的散列值看成数组的索引值。访问散列表和访问数组元素一样快速,它可以在常数时间内实现查找和插入操作。
由于无法通过散列值知道键的大小关系,因此散列表无法实现有序性操作。
2018-06-04 14:28:30 +08:00
### 1. 散列函数
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
对于一个大小为 M 的散列表散列函数能够把任意键转换为 [0, M-1] 内的正整数该正整数即为 hash 值。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
散列表有冲突的存在也就是两个不同的键可能有相同的 hash 值。
2018-04-06 22:46:59 +08:00
散列函数应该满足以下三个条件:
2018-06-04 14:28:30 +08:00
1. 一致性相等的键应当有相等的 hash 两个键相等表示调用 equals() 返回的值相等。
2. 高效性计算应当简便有必要的话可以把 hash 值缓存起来在调用 hash 函数时直接返回。
3. 均匀性所有键的 hash 值应当均匀地分布到 [0, M-1] 之间,这个条件至关重要,直接影响到散列表的性能。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
除留余数法可以将整数散列到 [0, M-1] 之间例如一个正整数 k计算 k%M 既可得到一个 [0, M-1] 之间的 hash 值。注意 M 必须是一个素数否则无法利用键包含的所有信息。例如 M  10<sup>k</sup>那么只能利用键的后 k 位。
2018-04-06 22:46:59 +08:00
对于其它数,可以将其转换成整数的形式,然后利用除留余数法。例如对于浮点数,可以将其表示成二进制形式,然后使用二进制形式的整数值进行除留余数法。
2018-06-04 14:28:30 +08:00
对于有多部分组合的键每部分都需要计算 hash 并且最后合并时需要让每部分 hash 值都具有同等重要的地位。可以将该键看成 R 进制的整数键中每部分都具有不同的权值。
2018-04-06 22:46:59 +08:00
例如,字符串的散列函数实现如下
```java
2018-06-04 14:28:30 +08:00
int hash = 0;
for(int i = 0; i < s.length(); i++)
    hash = (R * hash + s.charAt(i)) % M;
2018-04-06 22:46:59 +08:00
```
再比如,拥有多个成员的自定义类的哈希函数如下:
```java
2018-06-04 14:28:30 +08:00
int hash = (((day * R + month) % M) * R + year) % M;
2018-04-06 22:46:59 +08:00
```
2018-06-04 14:28:30 +08:00
R 通常取 31。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
Java 中的 hashCode() 实现了 hash 函数但是默认使用对象的内存地址值。在使用 hashCode() 函数时应当结合除留余数法来使用。因为内存地址是 32 位整数我们只需要 31 位的非负整数因此应当屏蔽符号位之后再使用除留余数法。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
int hash = (x.hashCode() & 0x7fffffff) % M;
2018-04-06 22:46:59 +08:00
```
2018-06-04 14:28:30 +08:00
使用 Java 自带的 HashMap 等自带的哈希表实现时只需要去实现 Key 类型的 hashCode() 函数即可。Java 规定 hashCode() 能够将键均匀分布于所有的 32 位整数Java 中的 String、Integer 等对象的 hashCode() 都能实现这一点。以下展示了自定义类型如何实现 hashCode()。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class Transaction{
    private final String who;
    private final Date when;
    private final double amount;
    public int hashCode(){
        int hash = 17;
        hash = 31 * hash + who.hashCode();
        hash = 31 * hash + when.hashCode();
        hash = 31 * hash + ((Double) amount).hashCode();
        return hash;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
### 2. 基于拉链法的散列表
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
拉链法使用链表来存储 hash 值相同的键从而解决冲突。此时查找需要分两步首先查找 Key 所在的链表然后在链表中顺序查找。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/b4252c85-6fb0-4995-9a68-a1a5925fbdb1.png" width="300"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
对于 N 个键M 条链表 (N>M)如果哈希函数能够满足均匀性的条件每条链表的大小趋向于 N/M因此未命中的查找和插入操作所需要的比较次数为 ~N/M。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 3. 基于线性探测法的散列表
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
线性探测法使用空位来解决冲突当冲突发生时向前探测一个空位来存储冲突的键。使用线性探测法数组的大小 M 应当大于键的个数 NM>N)。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/dbb8516d-37ba-4e2c-b26b-eefd7de21b45.png" width="400"/>
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class LinearProbingHashST<Key, Value> {
    private int N;
    private int M = 16;
    private Key[] keys;
    private Value[] vals;
    public LinearProbingHashST() {
        init();
    }
    public LinearProbingHashST(int M) {
        this.M = M;
        init();
    }
    private void init() {
        keys = (Key[]) new Object[M];
        vals = (Value[]) new Object[M];
    }
    private int hash(Key key) {
        return (key.hashCode() & 0x7fffffff) % M;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
**(一)查找**
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public Value get(Key key) {
    for (int i = hash(key); keys[i] != null; i = (i + 1) % M) {
        if (keys[i].equals(key)) {
            return vals[i];
        }
    }
    return null;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
**(二)插入**
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public void put(Key key, Value val) {
    int i;
    for (i = hash(key); keys[i] != null; i = (i + 1) % M) {
        if (keys[i].equals(key)) {
            vals[i] = val;
            return;
        }
    }
    keys[i] = key;
    vals[i] = val;
    N++;
    resize();
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
**(三)删除**
2018-04-06 22:46:59 +08:00
删除操作应当将右侧所有相邻的键值对重新插入散列表中。
```java
2018-06-04 14:28:30 +08:00
public void delete(Key key) {
    if (!contains(key)) return;
    int i = hash(key);
    while (!key.equals(keys[i])) {
        i = (i + 1) % M;
    }
    keys[i] = null;
    vals[i] = null;
    i = (i + 1) % M;
    while (keys[i] != null) {
        Key keyToRedo = keys[i];
        Value valToRedo = vals[i];
        keys[i] = null;
        vals[i] = null;
        N--;
        put(keyToRedo, valToRedo);
        i = (i + 1) % M;
    }
    N--;
    resize();
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
**(四)调整数组大小**
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
线性探测法的成本取决于连续条目的长度连续条目也叫聚簇。当聚簇很长时在查找和插入时也需要进行很多次探测。例如下图中 2~5 位置就是一个聚簇。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/386cd64f-7a9d-40e6-8c55-22b90ee2d258.png" width="400"/>
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
α = N/M α 称为利用率。理论证明 α 小于 1/2 时探测的预计次数只在 1.5  2.5 之间。
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
为了保证散列表的性能,应当调整数组的大小,使得 α 在 [1/4, 1/2] 之间。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
private void resize() {
    if (N >= M / 2) resize(2 * M);
    else if (N <= M / 8) resize(M / 2);
2018-04-06 22:46:59 +08:00
}
2018-06-04 14:28:30 +08:00
private void resize(int cap) {
    LinearProbingHashST<Key, Value> t = new LinearProbingHashST<>(cap);
    for (int i = 0; i < M; i++) {
        if (keys[i] != null) {
            t.put(keys[i], vals[i]);
        }
    }
    keys = t.keys;
    vals = t.vals;
    M = t.M;
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 应用
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 1. 各种符号表实现的比较
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
| 算法 | 插入 | 查找 | 是否有序 |
| :---: | :---: | :---: | :---: |
| 二分查找实现的有序表 | N | logN | yes |
| 二叉查找树 | logN | logN | yes |
| 2-3 查找树 | logN | logN | yes |
| 拉链法实现的散列表 | N/M | N/M | no |
| 线性探测法试下的散列表 | 1 | 1 | no |
2018-04-06 22:46:59 +08:00
应当优先考虑散列表,当需要有序性操作时使用红黑树。
2018-06-04 14:28:30 +08:00
### 2. Java 的符号表实现
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
- java.util.TreeMap红黑树
- java.util.HashMap拉链法的散列表
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
### 3. 集合类型
2018-04-06 22:46:59 +08:00
除了符号表,集合类型也经常使用,它只有键没有值,可以用集合类型来存储一系列的键然后判断一个键是否在集合中。
2018-06-04 14:28:30 +08:00
### 4. 稀疏向量乘法
2018-04-06 22:46:59 +08:00
2018-06-04 14:28:30 +08:00
当向量为稀疏向量时可以使用符号表来存储向量中的非 0 索引和值使得乘法运算只需要对那些非 0 元素进行即可。
2018-04-06 22:46:59 +08:00
```java
2018-06-04 14:28:30 +08:00
public class SparseVector {
    private HashMap<Integer, Double> hashMap;
    public SparseVector(double[] vector) {
        hashMap = new HashMap<>();
        for (int i = 0; i < vector.length; i++) {
            if (vector[i] != 0) {
                hashMap.put(i, vector[i]);
            }
        }
    }
    public double get(int i) {
        return hashMap.getOrDefault(i, 0.0);
    }
    public double dot(SparseVector other) {
        double sum = 0;
        for (int i : hashMap.keySet()) {
            sum += this.get(i) * other.get(i);
        }
        return sum;
    }
2018-04-06 22:46:59 +08:00
}
```
2018-06-04 14:28:30 +08:00
# 五、union-find
2018-05-09 17:15:36 +08:00
用于解决动态连通性问题,能动态连接两个点,并且判断两个点是否连通。
2018-06-04 14:28:30 +08:00
<img src="index_files/9d0a637c-6a8f-4f5a-99b9-fdcfa26793ff.png" width="400"/>
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
| 方法 | 描述 |
| :---: | :---: |
| UF(int N) | 构造一个大小为 N 的并查集 |
| void union(int p, int q) | 连接 p  q 节点 |
| int find(int p) | 查找 p 所在的连通分量 |
| boolean connected(int p, int q) | 判断 p  q 节点是否连通 |
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public class UF {
    private int[] id;
    public UF(int N) {
        id = new int[N];
        for (int i = 0; i < N; i++) {
            id[i] = i;
        }
    }
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
## quick-find
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
可以快速进行 find 操作即可以快速判断两个节点是否连通。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
同一连通分量的所有节点的 id 值相等。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
但是 union 操作代价却很高需要将其中一个连通分量中的所有节点 id 值都修改为另一个节点的 id 值。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/8f0cc500-5994-4c7a-91a9-62885d658662.png" width="350"/>
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public int find(int p) {
    return id[p];
2018-05-09 17:15:36 +08:00
}
2018-06-04 14:28:30 +08:00
public void union(int p, int q) {
    int pID = find(p);
    int qID = find(q);
    if (pID == qID) return;
    for (int i = 0; i < id.length; i++) {
        if (id[i] == pID) id[i] = qID;
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
## quick-union
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
可以快速进行 union 操作只需要修改一个节点的 id 值即可。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
但是 find 操作开销很大因为同一个连通分量的节点 id 值不同id 值只是用来指向另一个节点。因此需要一直向上查找操作直到找到最上层的节点。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/5d4a5181-65fb-4bf2-a9c6-899cab534b44.png" width="350"/>
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
    public int find(int p) {
        while (p != id[p]) p = id[p];
        return p;
    }
    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) return;
        id[pRoot] = qRoot;
    }
2018-05-09 17:15:36 +08:00
```
2018-06-04 14:28:30 +08:00
这种方法可以快速进行 union 操作但是 find 操作和树高成正比最坏的情况下树的高度为触点的数目。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/bfbb11e2-d208-4efa-b97b-24cd40467cd8.png" width="150"/>
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
## 加权 quick-union
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
为了解决 quick-union 的树通常会很高的问题加权 quick-union  union 操作时会让较小的树连接较大的树上面。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
理论研究证明加权 quick-union 算法构造的树深度最多不超过 logN。
2018-05-09 17:15:36 +08:00
2018-06-04 14:28:30 +08:00
<img src="index_files/a4c17d43-fa5e-4935-b74e-147e7f7e782c.png" width="200"/>
2018-05-09 17:15:36 +08:00
```java
2018-06-04 14:28:30 +08:00
public class WeightedQuickUnionUF {
    private int[] id;
    // 保存节点的数量信息
    private int[] sz;
    public WeightedQuickUnionUF(int N) {
        id = new int[N];
        sz = new int[N];
        for (int i = 0; i < N; i++) {
            id[i] = i;
            sz[i] = 1;
        }
    }
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }
    public int find(int p) {
        while (p != id[p]) p = id[p];
        return p;
    }
    public void union(int p, int q) {
        int i = find(p);
        int j = find(q);
        if (i == j) return;
        if (sz[i] < sz[j]) {
            id[i] = j;
            sz[j] += sz[i];
        } else {
            id[j] = i;
            sz[i] += sz[j];
        }
    }
2018-05-09 17:15:36 +08:00
}
```
2018-06-04 14:28:30 +08:00
## 路径压缩的加权 quick-union
在检查节点的同时将它们直接链接到根节点只需要在 find 中添加一个循环即可。
## 各种 union-find 算法的比较
| 算法 | union | find |
| :---: | :---: | :---: |
| quick-find | N | 1 |
| quick-union | 树高 | 树高 |
| 加权 quick-union | logN | logN |
| 路径压缩的加权 quick-union | 非常接近 1 | 非常接近 1 |
# 参考资料
- Sedgewick, Robert, and Kevin Wayne. _Algorithms_. Addison-Wesley Professional, 2011.
---bottom---CyC---
![](index_files/9d0a637c-6a8f-4f5a-99b9-fdcfa26793ff.png)
![](index_files/8f0cc500-5994-4c7a-91a9-62885d658662.png)
![](index_files/5d4a5181-65fb-4bf2-a9c6-899cab534b44.png)
![](index_files/bfbb11e2-d208-4efa-b97b-24cd40467cd8.png)
![](index_files/a4c17d43-fa5e-4935-b74e-147e7f7e782c.png)
![](index_files/ed7b96ac-6428-4bd5-9986-674c54c2a959.png)
![](index_files/c9a1de44-b1c0-4d13-a654-827d4ef8a723.png)
![](index_files/cdbe1d12-5ad9-4acb-a717-bbc822c2acf3.png)
![](index_files/8dfb4cc9-26da-45e7-b820-4576fa1cbb0e.png)
![](index_files/0c55e11c-d3ce-4cd8-b139-028aea6f40e3.png)
![](index_files/ab77240d-7338-4547-9183-00215e7220ec.png)
![](index_files/5aac64d3-2c7b-4f32-9e9a-1df2186f588b.png)
![](index_files/f3080f83-6239-459b-8e9c-03b6641f7815.png)
![](index_files/33ac2b23-cb85-4e99-bc41-b7b7199fad1c.png)
![](index_files/72f0ff69-138d-4e54-b7ac-ebe025d978dc.png)
![](index_files/b84ba6fb-312b-4e69-8c77-fb6eb6fb38d4.png)
![](index_files/51fb761d-8ce0-4472-92ff-2f227ac7888a.png)
![](index_files/1f039a45-6b91-4f31-a2c2-6c63eb8bdb56.png)
![](index_files/f9f9f993-8ece-4da7-b848-af9b438fad76.png)
![](index_files/8ae4550b-f0cb-4e4d-9e2b-c550538bf230.png)
![](index_files/fbe54203-c005-48f0-8883-b05e564a3173.png)
![](index_files/107a6a2b-f15b-4cad-bced-b7fb95258c9c.png)
![](index_files/4d741402-344d-4b7c-be01-e57184bcad0e.png)
![](index_files/be7dca03-12ec-456b-8b54-b1b3161f5531.png)
![](index_files/dd15a984-e977-4644-b127-708cddb8ca99.png)
![](index_files/fa568fac-ac58-48dd-a9bb-23b3065bf2dc.png)
![](index_files/ff396233-1bb1-4e74-8bc2-d7c90146f5dd.png)
![](index_files/7f38a583-2f2e-4738-97af-510e6fb403a7.png)
![](index_files/ef280699-da36-4b38-9735-9b048a3c7fe0.png)
![](index_files/4f48e806-f90b-4c09-a55f-ac0cd641c047.png)
![](index_files/3086c248-b552-499e-b101-9cffe5c2773e.png)
![](index_files/9110c1a0-8a54-4145-a814-2477d0128114.png)
![](index_files/e2f0d889-2330-424c-8193-198edebecff7.png)
![](index_files/af4639f9-af54-4400-aaf5-4e261d96ace7.png)
![](index_files/08427d38-8df1-49a1-8990-e0ce5ee36ca2.png)
![](index_files/b4252c85-6fb0-4995-9a68-a1a5925fbdb1.png)
![](index_files/dbb8516d-37ba-4e2c-b26b-eefd7de21b45.png)
![](index_files/386cd64f-7a9d-40e6-8c55-22b90ee2d258.png)