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插入排序的改进版的更多相关文章

  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-006归并排序(Mergesort)

    一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...

  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. 使用document.domain和iframe实现站内AJAX跨域

    站内AJAX跨域可以通过document.domain和iframe实现,比如www.css88.com.js.css88.com.css88.com这3个域名其实是3个不同的域,很多时候www.cs ...

  2. 面试题12:打印1到最大的n位数

    题目:输入数字n,按顺序打印出从1最大的n位十进制数.比如输入3,则打印出1.2.3一直到最大的3位数即999. 考点:大数问题. 解决方案:在字符串上模拟数字加法. <剑指Offer>上 ...

  3. java对Hbase的基本操作

     1.新建一个普通java项目,把${hbase}/lib/目录下的jar包全部导入 2.导出jar文件如下 3.运行 注意:需要先把jar文件导入到hbase路径里去,然后运行相应的类 4.查看数据 ...

  4. sass语法(1)

    文件后缀名 sass有两种后缀名文件:一种后缀名为sass,不使用大括号和分号:另一种就是我们这里使用的scss文件,这种和我们平时写的css文件格式差不多,使用大括号和分号 //文件后缀名为sass ...

  5. ContextMenuStrip 动态添加多级子菜单

    1.首先要实例化几个ToolStripItem(要为某一父菜单添加几个子菜单就实例化几个):方法如下: /*添加子菜单*/ ToolStripItem ts_1 = new ToolStripMenu ...

  6. Mac安装SSHFS挂载远程服务器上的文件夹到本地

    一.安装SSHFUS sshfs依赖于fuse,所以需要先安装fuse,这两个软件都可以在https://osxfuse.github.io/下载到. 注意安装顺序. 二.挂载文件夹到本地 输入一下命 ...

  7. Android Studio 开始运行错误

    /******************************************************************************** * Android Studio 开 ...

  8. C程序设计语言阅读笔记

    预处理器 ->.i  编译器 >.s 汇编器 >.o 链接器  --可执行文件   ------------------ math.h头文件包含各种数学函数的声明,所有函数都返回一个 ...

  9. Technocup 2019 C. Compress String

    一个字符串 $s$,你要把它分成若干段,有两种合法的段 1.段长为 $1$,代价为 $a$ 2.这个段是前面所有段拼起来组成的字符串的字串,代价为 $b$ 问最小代价 $|s| \leq 5000$ ...

  10. oracle+110个常用函数

    1.ASCII  返回与指定的字符对应的十进制数;  SQL> select ascii(A) A,ascii(a) a,ascii(0) zero,ascii( ) space from du ...