Graphic merge sort algorithm (java version)

Merge sort: using Thought (recursively) the partition method, the sequence of the entire array is divided into two sequences, two repeat sequences into respective sub-sequences, using recursive thought to solve one of the sub-problems.

Merge sort time complexity: O (n * lgn)
normalized sorted disease spatial complexity: O (n)

Merge sort of two core:
core a: merge the two ordered sequence. Comparing the first number of the two series, who will take small who then let the number of columns in a backward movement, one of known sequence moves to the last, another sequence was added behind in the order of the sequence have been routed to the .
Core II: The two parts of the array becomes an ordered sequence. The array is divided into group A, B, are each subdivided into two sub-groups, sub-out when only one data group, this group may be considered to be within the group has reached an orderly, and the two in combination. Such first recursive decomposition of the number of columns to complete the merger columns in merge sort.

java code:

public class MermeSort {
    //将两个有序序列进行合并
    public static void mermeArray(int[] arrs,int first, int mid, int last, int[] temp){
        int f = first;
        int m = mid;
        int n = mid + 1;
        int l = last;
        int k = 0;

        //将一个有序序列归并完成
        while(f <= m && n <= l){
            if(arrs[f] < arrs[n]){
                temp[k++] = arrs[f++];
            }else{
                temp[k++] = arrs[n++];
            }
        }

        //如果剩下左边的序列,则将左边的序列依次添加到temp后面
        while(f <= m){
            temp[k++] = arrs[f++];
        }

        //如果剩下的是右边的序列,则将右边的序列添加到temp后面
        while(n <= last){
            temp[k++] = arrs[n++];
        }

        //将temp中的有序序列依次拷贝到arrs序列相应的位置(first到last之间的这段序列)
        for (int i = 0; i < k; i++) {
            arrs[first+i] = temp[i];
        }
    }

    public static void mermeSort(int[] arrs, int first, int last, int[] temp){
        if(first < last){
            int mid = (first + last) / 2;

            mermeSort(arrs,first,mid,temp);//对first--last的前一半的元素进行排序

            mermeSort(arrs, mid+1, last, temp);//对first--last的后一半的元素进行排序

            mermeArray(arrs,first,mid,last,temp);//对first--last左右两边拍好的两个序列进行归并
        }
    }
}

A lot of people looked recursion, very ignorant force, I stop and analyze it again, and draw the figure below:
Write pictures described here

Published 77 original articles · won praise 39 · views 80000 +

Guess you like

Origin blog.csdn.net/qq_33824312/article/details/72696232