8种Java排序算法总结3(ZZ)

5、 归并排序

归并算法稳定,数组需要O(n)的额外空间,链表需要O(log(n))的额外空间,时间复杂度为O(nlog(n)),算法不是自适应的,不需要对数据的随机读取。

   
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[] 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&&highPtr<=upperBound){

           if(theArray[lowPtr]<theArray[highPtr]){

              workSpace[j++]=theArray[lowPtr++];

           }

           else{

              workSpace[j++]=theArray[highPtr++];

           }

       }

       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];

       }

    }

你可能感兴趣的:(java,算法,J#)