简介
要将一个数组排序,可以先(递归地)将它分为两半分别排序,然后将结果归并起来。
优点: 将任意长度为 N 的数组排序所需时间和 NlogN 成正比;
缺点:所需的额外空间和 N 成正比。
Basic Plan
- Divide array into two halves.
- Recursively sort each half.
- Merge two halves.
代码
1 | public class Merge { |
Mergesort: practical improvements
Use insertion sort for small subarrays
- Mergesort has too much overhead for tiny subarrays.
- Cutoff to insertion sort for ≈ 7 items.
1 | private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) |
Stop of already sorted.
- Is biggest item in first half <= smallest item in second half?
- Helps for partially-ordered arrays.
1 | private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) |