归并排序分为三个模块:
- merge():创建一个新的数组,作为排序前和排序后的过渡。
- recMerge():采用分治策略,用递归将数组不断对半分成小数组,直到只剩一个数值的时候。
- mergeSort():将第二步产生的数组进行归并排序。
package sort;
public class mergeSorted {
private long[] theArray;
private int nElems;
private int maxSize;
public mergeSorted(int size) {
maxSize = size;
theArray = new long[maxSize]; //数组初始化
nElems = 0;
}
public void insert(int data) {
if (nElems < maxSize) {
theArray[nElems] = data;
nElems++;
}
}
public void display() {
for(int j=0; j<nElems; j++) {
System.out.print(theArray[j] + " ");
}
System.out.println();
}
public void merge() {
long []workspace = new long[maxSize];
recMerge(workspace, 0, nElems-1);
}
public void recMerge(long []workspace, int low, int high) {
if(low==high){
return;
}
else
{
int mid = (low + high) / 2;
recMerge(workspace, low, mid);
recMerge(workspace, mid+1, high);
mergeSort(workspace, low, mid+1, high);
}
}
public void mergeSort(long []workspace, int lowPtr,
int highPtr, int higherBound) {
int j = 0;
int mid = highPtr - 1;
int lowerBound = lowPtr;
//n 控制将workspace中的数复制到theArray中的数量
int n = higherBound - lowerBound + 1;
while(lowPtr<=mid && highPtr <= higherBound) {
if(theArray[lowPtr] < theArray[highPtr]) {
workspace[j++] = theArray[lowPtr++];
}
else
{
workspace[j++] = theArray[highPtr++];
}
}
while(lowPtr <= mid) {
workspace[j++] = theArray[lowPtr++];
}
while(highPtr <= higherBound) {
workspace[j++] = theArray[highPtr++];
}
for(j=0; j<n; j++) {
theArray[lowerBound+j] = workspace[j];
}
}
public static void main(String[] args) {
int size = 100;
mergeSorted arr = new mergeSorted(size);
arr.insert(10);
arr.insert(12);
arr.insert(8);
arr.insert(6);
arr.insert(9);
arr.insert(20);
arr.insert(18);
arr.merge();
arr.display();
}
}