基本排序算法——归并排序

归并排序

package basic.sort;

import java.util.Arrays;
import java.util.Random;

public class MergeSort {
    
    private <AnyType extends Comparable<? super AnyType>>
    void mergeSort(AnyType[] arr){
        AnyType[] arrNew = (AnyType[]) new Comparable[arr.length];
        mergeSort(arr , arrNew , 0 , arr.length-1);
    }
    
    private <AnyType extends Comparable<? super AnyType>>
    void mergeSort(AnyType[] arr, AnyType[] arrNew ,int left , int right){
        if(left < right){
            int center = (left + right) /2 ;
            mergeSort(arr , arrNew, left , center );
            mergeSort(arr, arrNew, center +1 ,right);
            merge(arr,arrNew,left , center+1 , right);
        }
    }
    
    private <AnyType extends Comparable<? super AnyType>>
    void merge(AnyType[] arr, AnyType[] arrNew ,int leftPos , int rightPos , int rightEnd){
        int leftEnd = rightPos -1;
        int leftTmp = leftPos;
        int numElements = rightEnd - leftPos + 1;
        while(leftPos <= leftEnd && rightPos <= rightEnd){
            if(    arr[leftPos].compareTo(arr[rightPos]) <= 0){
                arrNew[leftTmp++] = arr[leftPos++];
            }else{
                arrNew[leftTmp++] = arr[rightPos++] ;
            }            
        }
        
        while(leftPos <= leftEnd){            
            arrNew[leftTmp++] = arr[leftPos++];                    
        }
        
        while(rightPos <= rightEnd){
            arrNew[leftTmp++] = arr[rightPos++];
        }    
        
        for(int i = 0 ; i < numElements ; i++ ){
            arr[rightEnd] = arrNew[rightEnd];
            rightEnd --;
        }
        
    }
    
    

    public static void main(String[] args) {
        Random rand = new Random();
        Integer[] arr = new Integer[10];
        for(int i = 0 ;i <10 ;i++){
            arr[i] = rand.nextInt(1000);
        }
        println("MergeSort () ");
        println(Arrays.toString(arr));
        MergeSort mergeSort = new MergeSort() ;
        mergeSort.mergeSort(arr);
        println(Arrays.toString(arr));
    }
    
    public static void println(String str){
        System.out.println(str);        
    }

}

 

posted @ 2013-08-30 12:29  远东悟语  阅读(197)  评论(0编辑  收藏  举报

我是徐冬冬