Recursive merge sort -merge

merge sort

5831283-882d4ec5b07d7c65.gif
image

He thought used recursively
divided in half to sort the results to merge (merge), then sort the two halves, has been so recursion.

Recursion (recursion)

Time and space consumption is relatively large. Each time a function call is required to allocate space in memory to save the stack parameters, return address, and temporary variables, and data to the stack and pushed inside the pop-up will take time.

To note basecase, termination conditions

A pair of front and back halves of the array through row sequence are merged

void merge(int array[], int leftpos, int rightpos, int lastpos)
{
    int* temparray = (int* )malloc(sizeof(int)*(lastpos - leftpos + 1));
    int i = leftpos;
    int j = rightpos;
    int k = 0;
    while((i<rightpos)&&(j<=lastpos)  ){
        if(array[i] <= array[j])
            temparray[k++] = array[i++];
        else
            temparray[k++] = array[j++];
    }
    while(i<rightpos)
        temparray[k++] = array[i++];
    while(j<=lastpos)
        temparray[k++] = array[j++];    
    
    for(i=0;i<=lastpos-leftpos;i++)
    {
        array[leftpos+i] = temparray[i]; 
    }
    free(temparray);
}

The array is divided into two halves, the first half of sorting, half of the sort, merge

void recursionmerge(int array[],int left, int right)
{
    if(left == right ) 
        return;
    int mid = (right+left)/2;

    recursionmerge(array,left,mid);
    recursionmerge(array,mid+1,right);
    merge(array,left,mid+1,right);
}

time complexity

Mean, preferably, the worst O (N * log2N)

Constantly in half (the number of points is logarithmic log2N, each is N so that N * log2N).

Space complexity
O (N)

Stable, sort Java objects using mergesort. Improved version called TimSort.

Guess you like

Origin blog.csdn.net/weixin_33991727/article/details/90983597