1 package com.iloveu.xxx;
2
3 public class MergeSort {
4
5 static final int SIZE = 15;
6
7 static void mergeOne(int a[],int b[],int n,int len)
8 {
9 int i,j,k,s,e;
10 s=0;
11 while(s+len<n){
12 e = s+2*len-1;
13 if(e>=n){//最后一段可能少于len个节点
14 e = n -1;
15 }
16 //相邻有序段合并
17 k=s;
18 i=s;
19 j=s+len;
20 while(i<s+len && j<=e){//如果两个有序表都未结束时,循环比较
21 if(a[i]<=a[j]){//如果较小的元素复制到数组b中
22 b[k++]=a[i++];
23 }else{
24 b[k++]=a[j++];
25 }
26 }
27 while(i<s+len){//未合并的部分复制到数组b中
28 b[k++]=a[i++];
29 }
30 while(j<=e){//未合并的部分复制到数组b中
31 b[k++]=a[j++];
32
33 }
34 s=e+1;//下一对有序段中左段的开始下标
35 }
36 if(s<n){//将剩余的一个有序段从数组a中复制到数组b中
37 for(;s<n;s++){
38 b[s] = a[s];
39 }
40
41 }
42 }
43
44 static void mergeSort(int a[],int n)//合并排序
45 {
46 int h,count,len,f;
47
48 count = 0;//排序步骤
49 len = 1;//有序序列的长度
50 f = 0;//变量f作标志
51
52 int[] p = new int[n];
53 while(len<n){
54 if(f==1){//交替在a和p之间合并
55 mergeOne(p,a,n,len);//p合并到a
56 }else{
57 mergeOne(a,p,n,len);//a合并到p
58 }
59 len = len*2;//增加有序序列长度
60 f=1-f;//使f值在0和1之间切换
61
62 count++;
63 System.out.printf("第"+count+"步排序结果:");//输出每步排序的结果
64 for(h=0;h<SIZE;h++){
65 System.out.printf(" "+a[h]);
66
67 }
68 System.out.printf("\n");
69 }
70 if(f==1){//如果进行了排序
71 for(h=0;h<n;h++){//将内存p中的数据复制回数组a
72 a[h]=p[h];
73 }
74 }
75 }
76
77 public static void main(String[] args) {
78 // TODO Auto-generated method stub
79 int[] shuzu=new int[SIZE];
80 int i;
81
82 for(i=0;i<SIZE;i++){
83 shuzu[i] = (int) (100+Math.random()*(100+1));//初始化数组
84 }
85
86 System.out.print("排序前的数组为:\n");//输出排序前的数组
87 for(i=0;i<SIZE;i++){
88 System.out.print(shuzu[i]+" ");
89 }
90 System.out.print("\n");
91
92 mergeSort(shuzu,SIZE);//排序操作
93
94 System.out.print("排序后的数组为:\n");
95 for(i=0;i<SIZE;i++){
96 System.out.print(shuzu[i]+" ");//输出排序后的数组
97 try {
98 Thread.sleep(1000);
99 } catch (InterruptedException e) {
100 // TODO Auto-generated catch block
101 e.printStackTrace();
102 }
103 }
104 System.out.print("\n");
105 }
106
107
108 }