算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)
一、
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)的更多相关文章
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)
一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)
一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版
package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)
一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)
一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-008排序算法的复杂度(比较次数的上下限)
一. 1. 2.
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-003比较算法及算法的可视化
一.介绍 1. 2. 二.代码 1. package algorithms.elementary21; /*********************************************** ...
- 算法Sedgewick第四版-第1章基础-001递归
一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...
- 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的
1. package algorithms.stacks13; /******************************************************************* ...
随机推荐
- 在Java中定义常量
方法一采用接口(Interface)的中变量默认为static final的特性. 方法二采用了Java 5.0中引入的Enum类型. 方法三采用了在普通类中使用static final修饰变量的方法 ...
- mysql中事务隔离级别可重复读说明
mysql中InnoDB引擎默认为可重复读的(REPEATABLE READ).修改隔离级别的方法,你可以在my.inf文件的[mysqld]中配置: transaction-isolation = ...
- UVALive - 4126 Password Suspects (AC自动机+状压dp)
给你m个字符串,让你构造一个字符串,包含所有的m个子串,问有多少种构造方法.如果答案不超过42,则按字典序输出所有可行解. 由于m很小,所以可以考虑状压. 首先对全部m个子串构造出AC自动机,每个节点 ...
- Tomcat的安装与环境配置
首先,下载地址为:http://tomcat.apache.org/,在左侧的列表中找到Download,找到自己要下载的Tomcat的版本.我下载的是Tomcat 7. 进入后出现如上右图界面.我选 ...
- java向excel写数据
package pymongo1; import java.io.File;import java.io.IOException;import java.io.OutputStream; import ...
- 软件架构设计 ADMEMS方法体系
ADMEMS是Architecture Design Method has been Extended to Method System的简称,是由CSAI顾问团架构设计专家组于2009年11月在第六 ...
- 一个Bug 差点让服务器的文件系统崩溃
昨天,公司的美国客户发邮件给我,说我的软件出问题了,我查来查去,发现居然是服务器上一个目录无法删除,一删除就报 cannot read from the source file or disk. 如果 ...
- c++11之二: 类成员变量初始化
在C++11中, 1.允许非静态成员变量的初始化有多种形式:初始化列表; 使用等号=或花括号{}进行就地的初始化. 可以为同一成员变量既声明就地的列表初始化,又在初始化列表中进行初始化,只不过初始化列 ...
- 蓝桥杯 算法训练 ALGO-152 8-2求完数
算法训练 8-2求完数 时间限制:50.0s 内存限制:256.0MB 问题描述 如果一个自然数的所有小于自身的因子之和等于该数,则称为完数.设计算法,打印1-9999之间的所有完数. 样例 ...
- Linux SPI驱动(一)
转载:http://www.cnblogs.com/lknlfy/p/3265019.html (原作者注:)根据我个人所知道的,Linux SPI一直是处于被“忽略”的角色,市场上大部分板子在板级文 ...