/** * 并归排序 * Create by Administrator * 2018/6/26 0026 * 下午 5:13 **/ public class DArray { private long[] theArray; private int nElens; public DArray(int max){ theArray = new long[max]; nElens = 0; } public void insert(long value){ theArray[nElens] = value; nElens++; } public void display(){ for (int i = 0; i < nElens; i++) { System.out.print(theArray[i] + " "); } System.out.println(""); } public void mergeSort(){ long[] workSpace = new long[nElens]; recMergeSort(workSpace,0,nElens-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 lowerBound1, int mid1, int upperBound) { int i = 0; int lowerBound = lowerBound1; int mid = mid1-1; int n = upperBound-lowerBound+1; while (lowerBound1 <= mid && mid1 <= upperBound){ if(theArray[lowerBound1] < theArray[mid1]){ workSpace[i++] = theArray[lowerBound1++]; }else{ workSpace[i++] = theArray[mid1++]; } } while (lowerBound1 <= mid){ workSpace[i++] = theArray[lowerBound1++]; } while (mid1 <= upperBound){ workSpace[i++] = theArray[mid1++]; } for (i = 0; i< n; i++){ theArray[lowerBound+i] = workSpace[i]; } } public static void main(String[] args) { int maxSize = 100; DArray array; array = new DArray(maxSize); array.insert(64); array.insert(21); array.insert(65); array.insert(1); array.insert(44); array.insert(20); array.insert(8); array.insert(15); array.insert(90); array.insert(76); array.insert(45); array.insert(55); array.display(); array.mergeSort(); array.display(); } }