算法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; /******************************************************************* ...
随机推荐
- jstat 简介(1)
1. jstat -gc pid 可以显示gc的信息,查看gc的次数,及时间. 其中最后五项,分别是young gc的次数,young gc的时间,full gc的次数,full gc的时间,gc的总 ...
- LeetCode OJ:Same Tree(相同的树)
Given two binary trees, write a function to check if they are equal or not. Two binary trees are con ...
- 条款42:了解typename的双重含义
typename在很多种情况下与class是完全相同的,例如下面的使用: templame<typename T> ...... template<class T> ..... ...
- JDBC操作简单实用了IOUtils
package cn.itcast.demo4; import java.io.FileInputStream; import java.io.FileOutputStream; import jav ...
- Codeforces Round #254(div2)B
就是看无向图有几个连通块,答案就是2n-num. 范围很小,就用矩阵来存图减少代码量. #include<iostream> #include<cstdio> #include ...
- 两个VLC实现播放串流测试
实现原理: 一个VLC打开视频文件发布串流(格式HTTP.RTP.RTSP等),另一个VLC打开串流播放 发布串流步骤: 1.菜单“媒体”->“流”,先添加视频文件.选择“串流”,如下图: 2. ...
- javascript网页复制功能-复制到粘贴板-兼容多数浏览器(不使用flash)
使用方法:clipBordCopy("hello Copy");//执行后复制hello Copy到粘贴板 通过 var result = clipBordCopy("h ...
- phyton方面相关书籍
0基础:<简明PYTHON教程>http://linux.chinaitlab.com/manual/Python_chinese/<与孩子一起学编程>http://book. ...
- 使用Asset Pipeline管理rails生产环境静态资源实现步骤
1. 修改项目中指向静态资源文件的链接 a) 访问静态资源文件 <%= stylesheet_link_tag "application", media: &q ...
- CreateMutex实现只能打开一个客户端
#include "stdafx.h" #include <Windows.h> #include <iostream> using namespace s ...