下面是排序代码:
public class DArray {
private long[] theArray;
private int nElems;
public DArray(int max){
theArray=new long[max];
nElems=0;
}
public void insert(long value){
theArray[nElems]=value;
nElems++;
}
public void display(){
for(int j=0;j<nElems;j++){
System.out.print(theArray[j]+" ");
}
System.out.println();
}
public void mergeSort(){
long[] workSpace=new long[nElems];
//开始位置为0,最大下标为总数量减1
recMergeSort(workSpace,0,nElems-1);
}
private void recMergeSort(long[] 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);
}
}
private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) {
// TODO Auto-generated method stub
int j=0;
int lowerBound=lowPtr;
int mid=highPtr-1;
//要归并的数量
int n=upperBound-lowerBound+1;
while(lowPtr<=mid&&highPtr<=upperBound){
if(theArray[lowPtr]<theArray[highPtr]){
workSpace[j++]=theArray[lowPtr++];
}else{
workSpace[j++]=theArray[highPtr++];
}
}
//将剩余没有比较的元素直接放入放入到workSpace数组当中去
while(lowPtr<=mid)
workSpace[j++]=theArray[lowPtr++];
while(highPtr<=upperBound)
workSpace[j++]=theArray[highPtr++];
//临时数组中的数据放入原始数组位置中,从指定的开始位置放
for(j=0;j<n;j++){
theArray[lowerBound+j]=workSpace[j];
}
}
}
对上面代码做简单解释:
recMergeSort函数当中lowerBou将一个数组一分为2分别进行归并,lowerBound与pperBound不相等时继续递归调用该函数,相等的时候返调用处,执行下一句函数。
下面是测试代码:
public class MergeSortApp {
public static void main(String[] args){
int maxSize=100;
DArray arr;
arr=new DArray(maxSize);
arr.insert(64);
arr.insert(87);
arr.insert(35);
arr.insert(94);
arr.insert(14);
arr.insert(2);
arr.insert(37);
arr.insert(4);
arr.insert(27);
arr.insert(96);
arr.insert(8);
System.out.print("未归并排序前的序列为: ");
arr.display();
System.out.print("归并排序后的序列为: ");
arr.mergeSort();
arr.display();
}
}
运行结果如下图所示:
参考资料:《大话数据结构》等。