Merge Sort



Merge Sort is an efficient method for sorting elements in an array, based on the following idea: if the first half of the array is sorted and the second half is also sorted, by merging these two halves, the entire array will be sorted.


Merge Sort is a typical example of a divide and conquer algorithm: it sorts a sequence delimited by indices st and dr:


In the following sequence, the tmp array is considered globally declared, of the same size as v:

void MergeSort(int v[], int st, int dr)
    {
        if(st < dr)
        {
            int m = (st + dr) / 2;
            MergeSort(v, st , m);
            MergeSort(v, m + 1 , dr);
            // Merging
            int i = st, j = m + 1, k = 0;
            while( i <= m && j <= dr )
                if( v[i] < v[j])
                    tmp[++k] = v[i++];
                else
                    tmp[++k] = v[j++];
            while(i <= m)
                tmp[++k] = v[i++];
            while(j <= dr)
                tmp[++k] = v[j++];
            for(i = st , j = 1 ; i <= dr ; i++ , j++)
                v[i] = tmp[j];
        }
    }

Observations:


Color Contrast

Text Size

Text Spacing

Reading Aids


In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!


Summary

In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!


Chatbot