package xwq.sort;
import xwq.util.StdIn;
import xwq.util.StdOut;
public class MergeSort {
public static void sort(Comparable a[]) {
Comparable[] acopy = new Comparable[a.length];
sort(a,acopy,0,a.length-1);
}
//归并排序
private static void sort(Comparable[] a,Comparable[] acopy,int low,int high) {
if( low >= high) return;
int mid = (low+high)/2;
//分
sort(a,acopy,low,mid);
sort(a,acopy,mid+1,high);
//合
merge(a,acopy,low,mid,high);
}
//合并两个已经递增有序的数组a[low,mid],a[low+1,high]
private static void merge(Comparable[] a,Comparable[] acopy,int low,int mid,int high) {
//copy待排序部分数组到辅助数组
for(int i = low;i<=high;i++)
acopy[i] = a[i];
//左半待合并数组a[low,mid],右半待合并数组a[low+1,high]
int i = low; //待合并左半部分数组起点位置
int j = mid+1;//待合并右半部分数组起点位置
int k = low; //合并数组起点位置
while(k<=high) {
//左半数组已全部插入
if(i>mid) a[k++] = acopy[j++];
//右半数组已全部插入
else if(j>high) a[k++] = acopy[i++];
//左半数组目前所指向的元素值<右半数组所指向的元素值
else if(less(acopy[i],acopy[j])) a[k++] = acopy[i++];
//左半数组目前所指向的元素值>=右半数组所指向的元素值
else a[k++] = acopy[j++];
}
}
//v<w
private static boolean less(Comparable v,Comparable w) {
return v.compareTo(w)<0;
}
//输出排序数组
public static void print(Comparable a[]) {
for(int i = 0;i<a.length;i++)
StdOut.print(a[i]+" ");
StdOut.println();
}
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
sort(a);
print(a);
}
}
排序-归并排序-基本
最新推荐文章于 2020-11-22 23:37:35 发布