排序_归并排序_递归
public class DArray { private long a[]; private int nElems; public DArray(int maxSize) { a=new long[maxSize]; nElems=0; } //插入 public void insert(long value) { a[nElems++]=value; } //显示 public void display() { for(int j=0;j<nElems;j++) System.out.print(a[j]+" "); System.out.println(); } public void mergeSort() { long[] workSpace=new long[nElems]; 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[] wordSpace, int lowerPtr, int hightPtr, int upperBound) { int j=0; int lowerBound=lowerPtr; int mid=hightPtr-1; int n=upperBound-lowerBound+1;//需要归并的数量 while(lowerPtr<=mid && hightPtr<=upperBound) { if(a[lowerPtr]<a[hightPtr]) wordSpace[j++]=a[lowerPtr++]; else wordSpace[j++]=a[hightPtr++]; }//取数组中最小的值放入临时数组中 /* * 4 7 8 10 || 3 5 20 50 * 比较4 与 3,3最小,临时数组[3] * 比较4与5 ,4 最小 ,临时数组[3,4] * 7 8 10||5 20 50 * 比较7 与 5,5最小,临时数组[3,4,5] * 比较7与 20,7最小。临时数组[3,4,5,7] * 比较8与20,8最小,临时数组[3,4,5,8] * 比较10与20,10最小,临时数组[3,4,5,8,10] * 剩下 ||20 50 * 最小按顺序存入临时数组中 */ //有可能有一边有剩余,但是不知道哪一边,所以每一边都写 while(lowerPtr<=mid) wordSpace[j++]=a[lowerPtr++]; while(hightPtr<=upperBound) wordSpace[j++]=a[hightPtr++]; for(j=0;j<n;j++) { a[lowerBound+j]=wordSpace[j]; } } }
public class Test { public static void main(String[] args) { int maxSize=100; DArray array=new DArray(maxSize); array.insert(77); array.insert(99); array.insert(44); array.insert(55); array.insert(22); array.insert(88); array.insert(11); array.insert(0); array.insert(66); array.insert(33); array.display(); array.mergeSort(); array.display(); } }