tonglin0325的个人主页

Java排序算法——归并排序

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.util.Arrays;

class Arrays_Merge{
private int[] arrays;
private int curNum;
//int[] workSpace;

public Arrays_Merge(int max) { //建立一个max长度的空数组
super();
arrays = new int[max];
curNum = 0;
}

public void insert(int value){ //往空的数组里面增加元素
arrays[curNum] = value;
curNum++;
}

public void display(){ //显示数组
System.out.println(Arrays.toString(arrays));
}

public void mergeSort(){
int[] arrays = new int[curNum];
recMergeSort(arrays, 0, curNum-1);
}

public void recMergeSort(int[] workSpace,int lowerBound,int upperBound){
if(lowerBound == upperBound)
return;
else
{
int mid = (lowerBound+upperBound)/2;
recMergeSort(workSpace,lowerBound,mid);
recMergeSort(workSpace,mid+1,upperBound);
merge(workSpace,lowerBound,mid+1,upperBound);
System.out.println("mid="+mid);
}
}

public void merge(int[] workSpace,int lowPtr,int highPtr,int upperBound){
int j=0;
int lowerBound = lowPtr;
int mid = highPtr-1;
int n = upperBound-lowerBound+1;

while(lowPtr<=mid &amp;&amp; highPtr<=upperBound){
if(arrays[lowPtr]<arrays[highPtr]){ //如果后面的小,就先放进新的数组中
workSpace[j++] = arrays[lowPtr++]; //如果运行第一行,就运行下面的第二个
System.out.println("1lowPtr="+(lowPtr-1)+" "+workSpace[j-1]);
}else{
workSpace[j++] = arrays[highPtr++]; //如果运行第二行,就运行下面的第一个
System.out.println("1highPtr="+(highPtr-1)+" "+(j-1)+"="+workSpace[j-1]);
}
}

while(lowPtr<=mid){ //以下两个只可能运行一个
workSpace[j++] = arrays[lowPtr++];
System.out.println("lowPtr="+(lowPtr-1)+" "+workSpace[j-1]);
}

while(highPtr<=upperBound){
workSpace[j++] = arrays[highPtr++];
System.out.println("highPtr="+(highPtr-1)+" "+workSpace[j-1]);
}

for(j=0;j<n;j++){
arrays[lowerBound+j] = workSpace[j];
}
}
}

public class MergeSort {

public static void main(String[] args) {
// TODO 自动生成的方法存根
int maxSize=10;
Arrays_Merge arr;
arr = new Arrays_Merge(maxSize);
arr.insert(9);
arr.insert(8);
arr.insert(7);
arr.insert(6);
arr.insert(5);
arr.insert(4);
arr.insert(3);
arr.insert(2);
arr.insert(1);
arr.display();
arr.mergeSort();
arr.display();
}

}