* 算法思想:将两个有序的数组归并成一个更大的有序数组。 * */ public class Merge { private static Comparable []b;//创建辅助数组 public static void sort(Comparable []a){ b=new Comparable[a.length]; sort(a,0,a.length-1); } private static void sort(Comparable []a,int low,int high){ while(low<high){ int mid=low+(low+high)/2; sort(a,0,mid); sort(a,mid+1,high); merge(a,low,mid,high); } } //原地归并的抽象方法----》将一个数组变为有序 public static void merge(Comparable []a,int low,int mid,int high) { int i = low, j = mid + 1; for (int k = low; k < high; k++) b[k] = a[k]; for (int k = low; k <= high; k++) { if (j > mid)//b表中后半部分大,将后半部分归并到a中 a[k] = b[j++]; else if (j > high)//前半部分大 a[k] = b[i++]; else if (less(b[j], b[i])) a[k] = b[j++]; else a[k] = b[i++]; } } //另外一种写法 public static void merge1(Comparable []a,int low,int mid,int high){ for(int k=low;k<high;k++) b[k]=a[k]; int i = low, j = mid + 1,k; for(k=low;i<=mid&&j<=high;k++){ if(less(b[j],b[i]))//逆序 a[k]=b[i++]; else a[k]=b[j++]; } //处理剩余的表,下面两个while只有一个会执行 while (i<=mid) a[k++]=b[i++];//前半部分的表未检测完 while(j<=high) a[k++]=b[j++]; } private static boolean less(Comparable v,Comparable w){//判断是否逆序 return v.compareTo(w)<0; } private static void exch(Comparable []a,int i,int j){ Comparable temp=a[i]; a[i]=a[j]; a[j]=temp; } public static void show(Comparable []a){ for(int i=0;i<a.length;i++) System.out.printf("%3d",a[i]); System.out.println(); } public static boolean isSorted(Comparable []a){ for (int i=1;i<a.length;i++) if(less(a[i],a[i-1])) return false; return true; } } /** * 自底向上的归并排序:先归并那些微型数组,然后再成对归并得到的子数组,直到我们将所有的数组归并到一起 * */ class MergeBU{ private static Comparable []b; public static void sort(Comparable []a){ int N=a.length; Comparable []b=new Comparable[N]; for(int sz=1;sz<N;sz+=sz) for(int low=0;low<N-sz;low+=sz+sz) Merge.merge(a,low,low+sz-1,Math.min(low+sz+sz-1,N-1)); } }
归并排序的实现方式
最新推荐文章于 2021-08-10 08:12:22 发布