排序-快速排序-优化-使用插入排序
2016-01-22 09:08
393 查看
package xwq.sort; import xwq.util.In; import xwq.util.StdOut; import xwq.util.StdRandom; /** * 使用插入排序对快速排序进行优化 * 大数组使用快速排序递归切分,小数组使用插入排序 * @author batman * */ public class QuickSortInsert { //M的最佳值是和系统相关的,但是5-15之间的任意值在大多数情况下都能令人满意 private static int M = 10; public static void sort(int[] a) { partition(a, 0, a.length - 1); } //数组划分 private static void partition(int[] a, int low, int high) { if(low>=high) return; //如果待排序数组长度小于等于M个数,使用插入排序 if((high-low+1) <= M) { insertSort(a,low,high); return; } int pos = StdRandom.uniform(low, high + 1);//随机生成一个基准位置 int pivot = a[pos];//基准值 int l = low,h = high; swap(a, low, pos); while (l < h) { while (l < h && a[h] >= pivot) h--; if (l < h) a[l++] = a[h]; while (l < h && a[l] <= pivot) l++; if (low < high) a[high--] = a[low]; } a[low] = pivot; partition(a,low,l-1); partition(a,l+1,high); } //插入排序 private static void insertSort(int[] a,int low,int high) { for(int i = low + 1;i <= high;i++) { int t = a[i];//待插入值 int j = i - 1;//从当前位置的上位开始比较 while(j >= low && a[j] > t){ a[j+1] = a[j]; j--; } a[j+1] = t; } } private static void swap(int a[], int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } public static void print(int a[]) { for (int i = 0; i < a.length; i++) StdOut.print(a[i] + " "); StdOut.println(); } //测试函数 public static void main(String[] args) { int[] a = In.readInts(args[0]); sort(a); print(a); } }
相关文章推荐
- jQuery禁用键盘后退屏蔽F5刷新及禁用右键单击
- HDU 1203 I NEED A OFFER!【01背包】
- Keystone集成LDAP
- Python 字符串操作方法大全
- Android教材 | 第三章 Android界面事件处理(二)—— 杰瑞教育原创教材试读
- xcode 插件
- Windows Server 2012 R2有哪些存储监控工具
- js中的异常处理try...catch使用介绍
- defer 与 async
- 解决LoadRunner运行负载测试You do not have a license for this Vuser type问题
- 连接scan ip 报 ORA-12545: 因目标主机或对象不存在,连接失败
- ASP.NET Web API中通过URI显示实体中的部分字段
- 消息队列
- 获取Android控件的宽和高
- 线程池 threadPoolExecutor详解
- jquery 简单设置图片自适应宽高(不完美)
- 堆和栈
- 排序-快速排序-基本-随机化快速排序
- xcode 改动整个项目名
- MFC学习(25)LPCTSTR和CString的关系