算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版
package algorithms.elementary21; import algorithms.util.StdIn;
import algorithms.util.StdOut; /******************************************************************************
* Compilation: javac InsertionX.java
* Execution: java InsertionX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt
* http://algs4.cs.princeton.edu/21sort/words3.txt
*
* Sorts a sequence of strings from standard input using an optimized
* version of insertion sort that uses half exchanges instead of
* full exchanges to reduce data movement..
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java InsertionX < 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 InsertionX < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
/**
* The <tt>InsertionX</tt> class provides static methods for sorting
* an array using an optimized version of insertion sort (with half exchanges
* and a sentinel).
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/ public class InsertionX { // This class should not be instantiated.
private InsertionX() { } /**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int N = a.length; // put smallest element in position to serve as sentinel
int exchanges = 0;
for (int i = N-1; i > 0; i--) {
if (less(a[i], a[i-1])) {
exch(a, i, i-1);
exchanges++;
}
}
if (exchanges == 0) return; // insertion sort with half-exchanges
for (int i = 2; i < N; i++) {
Comparable v = a[i];
int j = i;
while (less(v, a[j-1])) {
a[j] = a[j-1];
j--;
}
a[j] = v;
} 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) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
} // 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; insertion sorts them;
* and prints them to standard output in ascending order.
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
InsertionX.sort(a);
show(a);
} }
用二分查找法改进
package algorithms.elementary21; /******************************************************************************
* Compilation: javac BinaryInsertion.java
* Execution: java BinaryInsertion < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt
* http://algs4.cs.princeton.edu/21sort/words3.txt
*
* Sorts a sequence of strings from standard input using
* binary insertion sort with half exchanges.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java BinaryInsertion < 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 BinaryInsertion < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/ import algorithms.util.StdIn;
import algorithms.util.StdOut; /**
* The <tt>BinaryInsertion</tt> class provides a static method for sorting an
* array using an optimized binary insertion sort with half exchanges.
* <p>
* This implementation makes ~ N lg N compares for any array of length N.
* However, in the worst case, the running time is quadratic because the
* number of array accesses can be proportional to N^2 (e.g, if the array
* is reverse sorted). As such, it is not suitable for sorting large
* arrays (unless the number of inversions is small).
* <p>
* The sorting algorithm is stable and uses O(1) extra memory.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Ivan Pesin
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class BinaryInsertion { // This class should not be instantiated.
private BinaryInsertion() { } /**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 1; i < N; i++) { // binary search to determine index j at which to insert a[i]
Comparable v = a[i];
int lo = 0, hi = i;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (less(v, a[mid])) hi = mid;
else lo = mid + 1;
} // insetion sort with "half exchanges"
// (insert a[i] at index j and shift a[j], ..., a[i-1] to right)
for (int j = i; j > lo; --j)
a[j] = a[j-1];
a[lo] = v;
}
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;
} // exchange a[i] and a[j] (for indirect sort)
private static void exch(int[] a, int i, int j) {
int 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);
} // is the array sorted from a[lo] to a[hi]
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;
} // 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; insertion sorts them;
* and prints them to standard output in ascending order.
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
BinaryInsertion.sort(a);
show(a);
}
}
算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版的更多相关文章
- 算法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-006归并排序(Mergesort)
一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...
- 算法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; /******************************************************************* ...
随机推荐
- (转)libcurl库使用方法,好长,好详细。
一.ibcurl作为是一个多协议的便于客户端使用的URL传输库,基于C语言,提供C语言的API接口,支持DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP ...
- java web工程启动socket服务
1.新建web工程 2.自定义类 实现ServletContextListener 接口 在contextInitialized方法中启动socket服务的线程 在contextDestroyed方法 ...
- mysql_union all 纵向合并建表_20170123
年前事情比较多,博客不能每天更新了. 1.union all 纵向建表和left join 横向建表的数据结构区别 先贴代码 后面再补充 (#销售确认额 SELECT '05收货销售额' AS 标识, ...
- EF各版本增删查改及执行Sql语句
自从我开始使用Visual Studio 也已经经历了好几个版本了,而且这中间EF等框架的改变也算是比较多的.本篇文章记录下各个版本EF执行Sql语句和直接进行增删查改操作的区别,方便自己随时切换版本 ...
- 使用python实现两个文件夹里文件的对比(包含内容的对比)
#-*-coding:utf-8-*- #=============================================================================== ...
- k2 4.6.9安装记录-够复杂了
首先需要准备一台Windows server 2008R2 系统.可以从微软官方下载. 下载地址: http://www.microsoft.com/zh-cn/download/confirmati ...
- BZOJ1370:[Baltic2003]团伙
浅谈并查集:https://www.cnblogs.com/AKMer/p/10360090.html 题目传送门:https://lydsy.com/JudgeOnline/problem.php? ...
- Azure通过Vnet Peering和用户自定义路由(UDR)实现hub-spoken连接
Azure的Vnet Peering可以把Azure中不同的Vnet连接起来的技术.底层是通过对NVGRE的租户标签进行修改,实现了不同租户间的互通.这种技术非常类似传统网络中MPLS/VPN不同租户 ...
- hihoCoder#1322(树的判定)
时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定一个包含 N 个顶点 M 条边的无向图 G ,判断 G 是不是一棵树. 输入 第一个是一个整数 T ,代表测试数据的组 ...
- maven打包指定main函数的入口,生成依赖的包
为了使Jar包中指定Main方法位置和生成依赖包,需要在pom文件中加入如下配置: <build> <plugins> <plugin> <groupId&g ...