希尔排序
来源:互联网 发布:汇丰软件开发 待遇 编辑:程序博客网 时间:2024/06/09 23:59
//希尔排序//希尔排序是基于插入排序的快速排序算法//希尔排序为了加快速度简单地改进了插入排序,交换不相邻的元素以对数组的局部进行排序,并最终用插入排序将局部有序的数组排序package Algorithms;import edu.princeton.cs.algs4.StdIn;import edu.princeton.cs.algs4.StdOut;public class P163_Shell {private P163_Shell(){}public static void sort(Comparable[] a){//将a[]按升序排列int n = a.length;int h = 1;while (h < n / 3){h = 3 * h + 1;}while (h >= 1){//将数组变为h有序for (int i = h; i < n; i++){//将a[i]插入到a[i-h],a[i-2*h],a[i-3*h]...之中for (int j = i; j >= h && less(a[j], a[j - h]); j -= h){exch(a, j, j - h);}}assert isHsorted(a, h);h /= 3;}assert isSorted(a);}// 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; } 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; } // is the array h-sorted? private static boolean isHsorted(Comparable[] a, int h) { for (int i = h; i < a.length; i++) if (less(a[i], a[i-h])) 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]); } } public static void main(String[] args) {String[] a = StdIn.readAllStrings();P163_Shell.sort(a);show(a);}}
0 0
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 希尔排序
- 真正好用的js验证上传文件大小
- Android 清除缓存
- Android 数据库工具
- 源码-Oracle数据库管理-第九章-SQL查询-Part 4(集合运算和子查询)
- 中国的制造之路在哪?
- 希尔排序
- POJ3345 树形DP
- nginx平台初探
- A Taxonomy and Evaluation of Dense Two-Frame Stereo Correspondence Algorithms
- Android之退出系统
- 7. Reverse Integer
- Run SS as Daemon
- json转java实体
- 《从零开始学Swift》学习笔记(Day 38)——构造函数与存储属性初始化