[Learning] merge sort algorithm

1. Algorithm ideas:

  (1) to be sorted array is divided into two, the two recursive sorted array

  (2) the two merged into a sorted array ordered array.

      Implementation:

        a. providing two pointers, pointing to the beginning of the two arrays of numbers, comparing the pointer points, the smaller number is added an auxiliary array, the forward pointer, a pointer until overflow wherein

        b. Place the array does not overflow the remaining elements added to the auxiliary array

        c. Place the entire array are copied to the original auxiliary array

2. Code (JAVA):

public class mergesort{
    public static void mergeSort(int[] arr, int l, int r) {
        if(l<r){
            int mid=l+(r-l)/2;
            mergeSort(arr,l,mid);
            mergeSort(arr,mid+1,r);
            go (arr, l, r);
        }
    }
    
    public void merge(int[] arr,int l,int r){
        int[] tmp=new int[r-l+1];
        int mid=l+(r-l)/2;int p1=l;
        int p2=mid+1;
        int i=0;
        while(p1<=m&&p2<=r){
            if(arr[p1]<arr[p2])
                tmp[i++]=arr[p1++];
            else
                tmp[i++]=arr[p2++];
        }
        while(p1<=m)
            tmp[i++]=arr[p1];
        while(p2<=r)
            tmp[i++]=arr[p2];
        for(i=0;i<arr.length;i++){
            arr[l+i]=tmp[i];
        }
    }
}

 

3. Analysis of Algorithms:

  Time complexity: O (N * logN)

 

  

Guess you like

Origin www.cnblogs.com/teensSpirit-code-life/p/11722514.html