package 归并排序;
public class MergeSort {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[] input = new int[]{0,9,1,5,8,3,7,4,6,2};
mergeSort(input);
for(int k : input){
System.out.print(k + "\t");
}
System.out.println();
}
private static void mergeSort(int[] input) {
MSort(input,input,0,input.length-1);
}
private static void MSort(int[] SR, int[] TR1, int begin, int end) {
int tmp;
int[] TR2 = new int[end+1]; //TR2是存放排序后的子序列
if(begin == end){
TR1[begin] = SR[begin];
}else{
tmp = (begin + end)/2;
MSort(SR,TR2,begin,tmp);//将SR[begin ... tmp]归并为有序的TR2[begin ... tmp]
MSort(SR,TR2,tmp+1,end);//将SR[tmp+1 ... end]归并为有序的TR2[tmp+1 ... end]
Merge(TR2,TR1,begin,tmp,end);//将TR2[begin ... tmp]和TR2[tmp+1 ... end]归并为有序的TR1[begin ... end]
}
}
private static void Merge(int[] SR, int[] TR, int i, int m, int length) {
int j,k,l;
for(j=m+1,k=i;i<=m&&j<=length;k++){
if(SR[i] < SR[j]){
TR[k] = SR[i++];
}else{
TR[k] = SR[j++];
}
}
if(i<=m){
for(l=0;l<=m-i;l++){
TR[k+l] = SR[i+l];
}
}
if(j<=length){
for(l=0;l<=length-j;l++){
TR[k+l] = SR[j+l];
}
}
}
}
java专题——归并排序
最新推荐文章于 2024-11-03 11:01:20 发布