归并排序
来源:互联网 发布:机器人运动仿真软件 编辑:程序博客网 时间:2024/05/22 04:51
public class RecursiveMergeSort { public static void main(String[] args) { int[] data = new int[] { 5, 3, 6, 2, 1, 9, 4, 8, 7 }; print(data,"init"); // sort(data); mergeSort_insert(data, 0, data.length-1, 3); } public static void sort(int []array){ mergeSort(array, 0, array.length-1); } /** * * 合并排序 .<br> * void */ public static void merge(int []array,int left,int center,int right){ int []temp = new int[array.length]; //缓存左侧数组第一个元素下标 int tmp=left; //右侧数组第一个元素下标 int middle=center+1; //临时数组第一个元素下标 int index=left; while(left<=center && middle<=right){ if(array[left]<array[middle]){ temp[index++]=array[left++]; }else{ temp[index++]=array[middle++]; } } while(left<=center){ temp[index++]=array[left++]; } while(middle<=right){ temp[index++]=array[middle++]; } while(tmp<=right){ array[tmp]=temp[tmp++]; } print(array,"merge"); } /** * * 分解排序 .<br> * * @param a * @param b * @param p * @param q void */ public static void mergeSort(int []array,int left,int right){ if(left >= right) return; int center = (left+right)/2; mergeSort(array,left,center); mergeSort(array,center+1,right); merge(array,left,center,right); } public static void mergeSort_insert(int []array,int left,int right,int k){ if(left >= right) return; int center = (left+right)/2; if(right-left+1>k){ mergeSort_insert(array,left,center,k); mergeSort_insert(array,center+1,right,k); merge(array, left,center,right); }else{ insert_sort(array,left,right); print(array,"insert"); } } public static void insert_sort(int []array,int left,int right){ for(int i=left+1 ;i<=right;i++){ int temp=array[i]; int j=i-1; while(j>=left && array[j]>array[i]){ array[i] = array[j]; j--; } array[++j] = temp; } } public static void print(int[] data,String type) { System.out.print(type+"\t"); for (int i = 0; i < data.length; i++) { System.out.print(data[i] + "\t"); } System.out.println(); } }
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- eclipse使用心得
- JavaScript中关于事件绑定、冒泡、捕获和执行顺序
- poj 2443 bitset 或 状态压缩
- USACO-Section1.1 Broken Necklace [动态规划]
- [安卓基础]学习第七天
- 归并排序
- 最长回文串
- 【七日牧函】来一场爱心大冒险
- python的web开发框架django学习笔记
- 排序--折半插入排序
- BANANAPI 修改启动直接进入系统
- FAQ停用词表
- QT源程序与编译方式
- Java使用Condition唤醒指定线程