一、

1.特点

(1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursively), and then merge the results. As you will see, one of mergesort’s most attractive properties is that it guarantees to sort any array of N items in time proportional to N log N. Its prime disadvantage is that it uses extra space proportional to N.

(2)

(3)

(4)

(5)

2.缺点

■ Mergesort is not optimal with respect to space usage.
■ The worst case may not be likely in practice.
■ Operations other than compares (such as array accesses) may be important.
■ One can sort certain data without using any compares.
Thus, we shall be considering several other sorting methods in this book.

3.介绍

二、

1.代码

 package algorithms.mergesort22;

 import algorithms.util.StdIn;
import algorithms.util.StdOut; /******************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/22mergesort/tiny.txt
* http://algs4.cs.princeton.edu/22mergesort/words3.txt
*
* Sorts a sequence of strings from standard input using mergesort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Merge < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Merge < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/ /**
* The <tt>Merge</tt> class provides static methods for sorting an
* array using mergesort.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* For an optimized version, see {@link MergeX}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Merge { // This class should not be instantiated.
private Merge() { } // stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
// precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
assert isSorted(a, lo, mid);
assert isSorted(a, mid+1, hi); // copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
} // merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
} // postcondition: a[lo .. hi] is sorted
assert isSorted(a, lo, hi);
} // mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
} /**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
} /***************************************************************************
* Helper sorting functions.
***************************************************************************/ // is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
} // exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
} /***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
} private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
} /***************************************************************************
* Index mergesort.
***************************************************************************/
// stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) { // copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = index[k];
} // merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) index[k] = aux[j++];
else if (j > hi) index[k] = aux[i++];
else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];
else index[k] = aux[i++];
}
} /**
* Returns a permutation that gives the elements in the array in ascending order.
* @param a the array
* @return a permutation <tt>p[]</tt> such that <tt>a[p[0]]</tt>, <tt>a[p[1]]</tt>,
* ..., <tt>a[p[N-1]]</tt> are in ascending order
*/
public static int[] indexSort(Comparable[] a) {
int N = a.length;
int[] index = new int[N];
for (int i = 0; i < N; i++)
index[i] = i; int[] aux = new int[N];
sort(a, index, aux, 0, N-1);
return index;
} // mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, index, aux, lo, mid);
sort(a, index, aux, mid + 1, hi);
merge(a, index, aux, lo, mid, hi);
} // print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
} /**
* Reads in a sequence of strings from standard input; mergesorts them;
* and prints them to standard output in ascending order.
*/
public static void main(String[] args) {
//String[] a = StdIn.readAllStrings();
Integer[] a = {3,1,2,5,4};
Merge.sort(a);
show(a);
}
}

2.可视化

package algorithms.mergesort22;

import algorithms.util.StdDraw;
import algorithms.util.StdRandom; /******************************************************************************
* Compilation: javac MergeBars.java
* Execution: java MergeBars M N
* Dependencies: StdDraw.java
*
* Sort N random real numbers between 0 and 1 (with M disintct values)
* using mergesort with cutoff to insertion sort.
*
* Visualize the results by ploting bars with heights proportional
* to the values.
*
* % java MergeBars 1000 96
*
* Comments
* --------
* - suggest removing the 10% default StdDraw border
* - if image is too large, it may not display properly but you can
* still save it to a file
*
******************************************************************************/ public class MergeBars {
private static final int VERTICAL = 70;
private static final int CUTOFF = 12; private static int numberOfRows;
private static int row = 0; // stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
public static void merge(double[] a, double[] aux, int lo, int mid, int hi) { // copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
} // merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
} // mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(double[] a, double[] aux, int lo, int hi) {
int N = hi - lo + 1;
if (N <= CUTOFF) {
insertionSort(a, lo, hi);
show(a, lo, hi);
return;
}
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
show(a, lo, hi);
} public static void sort(double[] a) {
double[] aux = new double[a.length];
sort(a, aux, 0, a.length-1);
} // sort from a[lo] to a[hi] using insertion sort
private static void insertionSort(double[] a, int lo, int hi) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
} private static boolean less(double v, double w) {
return v < w;
} private static void exch(double[] a, int i, int j) {
double t = a[i];
a[i] = a[j];
a[j] = t;
} // draw one row of trace
private static void show(double[] a, int lo, int hi) {
double y = numberOfRows - row - 1;
for (int k = 0; k < a.length; k++) {
if (k < lo) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else if (k > hi) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledRectangle(k, y + a[k]*.25, .25, a[k]*.25);
}
row++;
} public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
if (args.length == 3) {
long seed = Long.parseLong(args[2]);
StdRandom.setSeed(seed);
}
double[] a = new double[N];
double[] b = new double[N];
for (int i = 0; i < N; i++) {
a[i] = (1 + StdRandom.uniform(M)) / (double) M;
b[i] = a[i];
} // precompute the number of rows
StdDraw.show(0);
numberOfRows = 0;
sort(b);
numberOfRows = row;
row = 0;
StdDraw.clear(); StdDraw.setCanvasSize(800, numberOfRows*VERTICAL);
StdDraw.show(0);
StdDraw.square(.5, .5, .5);
StdDraw.setXscale(-1, N);
StdDraw.setYscale(-0.5, numberOfRows);
StdDraw.show(0);
sort(a);
StdDraw.show(0);
}
}

算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

  3. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版

    package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...

  4. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)

    一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...

  5. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

    一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...

  6. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-008排序算法的复杂度(比较次数的上下限)

    一. 1. 2.

  7. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-003比较算法及算法的可视化

    一.介绍 1. 2. 二.代码 1. package algorithms.elementary21; /*********************************************** ...

  8. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  9. 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

    1. package algorithms.stacks13; /******************************************************************* ...

随机推荐

  1. Eclipse插件开发_异常_01_java.lang.RuntimeException: No application id has been found.

    一.异常现象 在运行RCP程序时,出现 java.lang.RuntimeException: No application id has been found. at org.eclipse.equ ...

  2. linux monitor and maintanence

    @cacti 1.install epel extends source 2.install lamp use yum method yum install -y httpd php php-mysq ...

  3. 剑指offer--20.矩形覆盖

    链接:https://www.nowcoder.com/questionTerminal/72a5a919508a4251859fb2cfb987a0e6来源:牛客网 @DanielLea 思路分析: ...

  4. POJ - 2891 Strange Way to Express Integers (扩展中国剩余定理)

    题目链接 扩展CRT模板题,原理及证明见传送门(引用) #include<cstdio> #include<algorithm> using namespace std; ty ...

  5. AMD 规范

    AMD(异步模块定义)是为浏览器环境设计的,因为 CommonJS 模块系统是同步加载的,当前浏览器环境还没有准备好同步加载模块的条件. AMD 定义了一套 JavaScript 模块依赖异步加载标准 ...

  6. 学习动态性能表(13)--v$open_cursor

    学习动态性能表 第13篇--V$OPEN_CURSOR  2007.6.8 本视图列出session打开的所有cursors,很多时候都将被用到,比如:你可以通过它查看各个session打开的curs ...

  7. COGS 2259 异化多肽 —— 生成函数+多项式求逆

    题目:http://cogs.pro:8080/cogs/problem/problem.php?pid=2259 如果构造生成函数是许多个 \( (1+x^{k}+x^{2k}+...) \) 相乘 ...

  8. xftp连接不上阿里云服务器

    打开xftp默认是使用FTP协议,要连接到云服务器,需要将协议改为SFTP 连接成功

  9. 利用PowerDesigner设计数据库

    PowerDesigner非常强大, 可以利用它完成数据库的设计. 1.下载地址:http://pan.baidu.com/s/1DsLrg 2.表设计: 建立概念数据模型(Conceptual Da ...

  10. 运行flask程序

    Command Line Interface Installing Flask installs the flask script, a Click command line interface, i ...