merge-sort

Divide and conquer is the core idea of merge sort. You can recursively divide the original array into two sub-arrays, until each sub-array only has one element. At the last, it looks like a tree, the root node is the original array and the leaf node is the array which only has one element. Then from bottom to up, merge two adjacent arrays from the same level, and organize them into an ordered array.

The detail steps of this algorithm are as follows:

1.      Calculate the element position in middle.

2.      Separate the original array to two sub-arrays, one is from start to the middle position and the other is from the position next the middle one to the end of the array. Make the two sub-arrays as the new argument and then call the merge sort method itself respectively.

3.      Merge the two sub-arrays and ensure that the merge result is ordered.

How to make sure the merge result is ordered?

Firstly, we should clearly know that each sub-array had been ordered.

Then, choose the first element of each sub-array, and then compare the two elements, put the smaller element to the result array, and then we should get the next element from the array in which the smaller element is located.

If one of the sub-arrays are empty, then add the rest elements of the other sub-arrays to the end of the result array.

4.      Quit the recursion if the end position is less than the start position.

Its time complexity is O(nlgn).

The following is the implement of merge-sort by java.

public void mergeSort(int[] A, int s, int e){
    if(s < e){
        int m = (e + s)/2;
        mergeSort(A,s,m);
        mergeSort(A,m+1,e);
        mergeSorted(A,s,m,e);
    }
}

private void mergeSorted(int[] A,int s, int m,int e){
    int[] L = new int[m-s+1];
    int[] R = new int[e-m];
    for(int i = 0;i < L.length;i++){
        L[i] = A[s+i];
    }
    for(int j = 0;j < R.length;j++){
        R[j] = A[m+1+j];
    }
    int i = 0,j = 0;
    for(int k = s;k < e-s+1;k++){
        if(i > L.length - 1){
            A[k] = R[j];
            j++;
        }else if(j > R.length - 1 ||L[i] <= R[j]){
            A[k] = L[i];
            i++;
        }else{
            A[k] = R[j];
            j++;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值