{"id":25089,"date":"2017-10-15T14:15:00","date_gmt":"2017-10-15T08:45:00","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25089"},"modified":"2017-10-15T14:15:00","modified_gmt":"2017-10-15T08:45:00","slug":"merge-sort","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/merge-sort\/","title":{"rendered":"Merge Sort"},"content":{"rendered":"<p>Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.<span id=\"more-142308\"><\/span> <strong>The merge() function<\/strong> is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C implementation for details.<\/p>\n<p><strong>MergeSort(arr[], l, r)\u00a0<\/strong><\/p>\n<p>If r &gt; l<\/p>\n<p><strong>1. <\/strong>Find the middle point to divide the array into two halves: middle m = (l+r)\/2<\/p>\n<p><strong> 2. <\/strong>Call mergeSort for first half: Call mergeSort(arr, l, m)<\/p>\n<p><strong>3.<\/strong> Call mergeSort for second half: Call mergeSort(arr, m+1, r)<\/p>\n<p><strong>4. <\/strong>Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r)<\/p>\n<p>The following diagram from wikipedia shows the complete merge sort process for an example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge processes comes into action and starts merging arrays back till the complete array is merged.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25090\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Merge-Sort.png\" alt=\"merge sort\" width=\"618\" height=\"595\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Merge-Sort.png 618w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Merge-Sort-300x289.png 300w\" sizes=\"(max-width: 618px) 100vw, 618px\" \/><\/p>\n[ad type=&#8221;banner&#8221;]\n<p>C and C++<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C AND C++<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* C program for Merge Sort *\/<br\/>#include&lt;stdlib.h&gt;<br\/>#include&lt;stdio.h&gt;<br\/> <br\/>\/\/ Merges two subarrays of arr[].<br\/>\/\/ First subarray is arr[l..m]<br\/>\/\/ Second subarray is arr[m+1..r]<br\/>void merge(int arr[], int l, int m, int r)<br\/>{<br\/>    int i, j, k;<br\/>    int n1 = m - l + 1;<br\/>    int n2 =  r - m;<br\/> <br\/>    \/* create temp arrays *\/<br\/>    int L[n1], R[n2];<br\/> <br\/>    \/* Copy data to temp arrays L[] and R[] *\/<br\/>    for (i = 0; i &lt; n1; i++)<br\/>        L[i] = arr[l + i];<br\/>    for (j = 0; j &lt; n2; j++)<br\/>        R[j] = arr[m + 1+ j];<br\/> <br\/>    \/* Merge the temp arrays back into arr[l..r]*\/<br\/>    i = 0; \/\/ Initial index of first subarray<br\/>    j = 0; \/\/ Initial index of second subarray<br\/>    k = l; \/\/ Initial index of merged subarray<br\/>    while (i &lt; n1 &amp;&amp; j &lt; n2)<br\/>    {<br\/>        if (L[i] &lt;= R[j])<br\/>        {<br\/>            arr[k] = L[i];<br\/>            i++;<br\/>        }<br\/>        else<br\/>        {<br\/>            arr[k] = R[j];<br\/>            j++;<br\/>        }<br\/>        k++;<br\/>    }<br\/> <br\/>    \/* Copy the remaining elements of L[], if there<br\/>       are any *\/<br\/>    while (i &lt; n1)<br\/>    {<br\/>        arr[k] = L[i];<br\/>        i++;<br\/>        k++;<br\/>    }<br\/> <br\/>    \/* Copy the remaining elements of R[], if there<br\/>       are any *\/<br\/>    while (j &lt; n2)<br\/>    {<br\/>        arr[k] = R[j];<br\/>        j++;<br\/>        k++;<br\/>    }<br\/>}<br\/> <br\/>\/* l is for left index and r is right index of the<br\/>   sub-array of arr to be sorted *\/<br\/>void mergeSort(int arr[], int l, int r)<br\/>{<br\/>    if (l &lt; r)<br\/>    {<br\/>        \/\/ Same as (l+r)\/2, but avoids overflow for<br\/>        \/\/ large l and h<br\/>        int m = l+(r-l)\/2;<br\/> <br\/>        \/\/ Sort first and second halves<br\/>        mergeSort(arr, l, m);<br\/>        mergeSort(arr, m+1, r);<br\/> <br\/>        merge(arr, l, m, r);<br\/>    }<br\/>}<br\/> <br\/>\/* UTILITY FUNCTIONS *\/<br\/>\/* Function to print an array *\/<br\/>void printArray(int A[], int size)<br\/>{<br\/>    int i;<br\/>    for (i=0; i &lt; size; i++)<br\/>        printf(&quot;%d &quot;, A[i]);<br\/>    printf(&quot;\\n&quot;);<br\/>}<br\/> <br\/>\/* Driver program to test above functions *\/<br\/>int main()<br\/>{<br\/>    int arr[] = {12, 11, 13, 5, 6, 7};<br\/>    int arr_size = sizeof(arr)\/sizeof(arr[0]);<br\/> <br\/>    printf(&quot;Given array is \\n&quot;);<br\/>    printArray(arr, arr_size);<br\/> <br\/>    mergeSort(arr, 0, arr_size - 1);<br\/> <br\/>    printf(&quot;\\nSorted array is \\n&quot;);<br\/>    printArray(arr, arr_size);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Java<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/* Java program for Merge Sort *\/<br\/>class MergeSort<br\/>{<br\/>    \/\/ Merges two subarrays of arr[].<br\/>    \/\/ First subarray is arr[l..m]<br\/>    \/\/ Second subarray is arr[m+1..r]<br\/>    void merge(int arr[], int l, int m, int r)<br\/>    {<br\/>        \/\/ Find sizes of two subarrays to be merged<br\/>        int n1 = m - l + 1;<br\/>        int n2 = r - m;<br\/> <br\/>        \/* Create temp arrays *\/<br\/>        int L[] = new int [n1];<br\/>        int R[] = new int [n2];<br\/> <br\/>        \/*Copy data to temp arrays*\/<br\/>        for (int i=0; i&lt;n1; ++i)<br\/>            L[i] = arr[l + i];<br\/>        for (int j=0; j&lt;n2; ++j)<br\/>            R[j] = arr[m + 1+ j];<br\/> <br\/> <br\/>        \/* Merge the temp arrays *\/<br\/> <br\/>        \/\/ Initial indexes of first and second subarrays<br\/>        int i = 0, j = 0;<br\/> <br\/>        \/\/ Initial index of merged subarry array<br\/>        int k = l;<br\/>        while (i &lt; n1 &amp;&amp; j &lt; n2)<br\/>        {<br\/>            if (L[i] &lt;= R[j])<br\/>            {<br\/>                arr[k] = L[i];<br\/>                i++;<br\/>            }<br\/>            else<br\/>            {<br\/>                arr[k] = R[j];<br\/>                j++;<br\/>            }<br\/>            k++;<br\/>        }<br\/> <br\/>        \/* Copy remaining elements of L[] if any *\/<br\/>        while (i &lt; n1)<br\/>        {<br\/>            arr[k] = L[i];<br\/>            i++;<br\/>            k++;<br\/>        }<br\/> <br\/>        \/* Copy remaining elements of R[] if any *\/<br\/>        while (j &lt; n2)<br\/>        {<br\/>            arr[k] = R[j];<br\/>            j++;<br\/>            k++;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Main function that sorts arr[l..r] using<br\/>    \/\/ merge()<br\/>    void sort(int arr[], int l, int r)<br\/>    {<br\/>        if (l &lt; r)<br\/>        {<br\/>            \/\/ Find the middle point<br\/>            int m = (l+r)\/2;<br\/> <br\/>            \/\/ Sort first and second halves<br\/>            sort(arr, l, m);<br\/>            sort(arr , m+1, r);<br\/> <br\/>            \/\/ Merge the sorted halves<br\/>            merge(arr, l, m, r);<br\/>        }<br\/>    }<br\/> <br\/>    \/* A utility function to print array of size n *\/<br\/>    static void printArray(int arr[])<br\/>    {<br\/>        int n = arr.length;<br\/>        for (int i=0; i&lt;n; ++i)<br\/>            System.out.print(arr[i] + &quot; &quot;);<br\/>        System.out.println();<br\/>    }<br\/> <br\/>    \/\/ Driver method<br\/>    public static void main(String args[])<br\/>    {<br\/>        int arr[] = {12, 11, 13, 5, 6, 7};<br\/> <br\/>        System.out.println(&quot;Given Array&quot;);<br\/>        printArray(arr);<br\/> <br\/>        MergeSort ob = new MergeSort();<br\/>        ob.sort(arr, 0, arr.length-1);<br\/> <br\/>        System.out.println(&quot;\\nSorted array&quot;);<br\/>        printArray(arr);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>&nbsp;<\/p>\n<p>Python<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for implementation of MergeSort<br\/> <br\/># Merges two subarrays of arr[].<br\/># First subarray is arr[l..m]<br\/># Second subarray is arr[m+1..r]<br\/>def merge(arr, l, m, r):<br\/>    n1 = m - l + 1<br\/>    n2 = r- m<br\/> <br\/>    # create temp arrays<br\/>    L = [0] * (n1)<br\/>    R = [0] * (n2)<br\/> <br\/>    # Copy data to temp arrays L[] and R[]<br\/>    for i in range(0 , n1):<br\/>        L[i] = arr[l + i]<br\/> <br\/>    for j in range(0 , n2):<br\/>        R[j] = arr[m + 1 + j]<br\/> <br\/>    # Merge the temp arrays back into arr[l..r]<br\/>    i = 0     # Initial index of first subarray<br\/>    j = 0     # Initial index of second subarray<br\/>    k = l     # Initial index of merged subarray<br\/> <br\/>    while i &lt; n1 and j &lt; n2 :<br\/>        if L[i] &lt;= R[j]:<br\/>            arr[k] = L[i]<br\/>            i += 1<br\/>        else:<br\/>            arr[k] = R[j]<br\/>            j += 1<br\/>        k += 1<br\/> <br\/>    # Copy the remaining elements of L[], if there<br\/>    # are any<br\/>    while i &lt; n1:<br\/>        arr[k] = L[i]<br\/>        i += 1<br\/>        k += 1<br\/> <br\/>    # Copy the remaining elements of R[], if there<br\/>    # are any<br\/>    while j &lt; n2:<br\/>        arr[k] = R[j]<br\/>        j += 1<br\/>        k += 1<br\/> <br\/># l is for left index and r is right index of the<br\/># sub-array of arr to be sorted<br\/>def mergeSort(arr,l,r):<br\/>    if l &lt; r:<br\/> <br\/>        # Same as (l+r)\/2, but avoids overflow for<br\/>        # large l and h<br\/>        m = (l+(r-1))\/2<br\/> <br\/>        # Sort first and second halves<br\/>        mergeSort(arr, l, m)<br\/>        mergeSort(arr, m+1, r)<br\/>        merge(arr, l, m, r)<br\/> <br\/> <br\/># Driver code to test above<br\/>arr = [12, 11, 13, 5, 6, 7]<br\/>n = len(arr)<br\/>print (&quot;Given array is&quot;)<br\/>for i in range(n):<br\/>    print (&quot;%d&quot; %arr[i]),<br\/> <br\/>mergeSort(arr,0,n-1)<br\/>print (&quot;\\n\\nSorted array is&quot;)<br\/>for i in range(n):<br\/>    print (&quot;%d&quot; %arr[i]),<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<p>Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13<\/p>\n<p><strong>Time Complexity:<\/strong> Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.<br \/>\nT(n) = 2T(n\/2) + <img decoding=\"async\" class=\"ql-img-inline-formula quicklatex-auto-format\" title=\"Rendered by QuickLaTeX.com\" src=\"http:\/\/www.geeksforgeeks.org\/wp-content\/ql-cache\/quicklatex.com-d477324801a84e26258bba0227dfea27_l3.svg\" alt=\"\\Theta(n)\" width=\"38\" height=\"18\" \/><br \/>\nThe above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is <img decoding=\"async\" class=\"ql-img-inline-formula quicklatex-auto-format\" title=\"Rendered by QuickLaTeX.com\" src=\"http:\/\/www.geeksforgeeks.org\/wp-content\/ql-cache\/quicklatex.com-7ace2f489b005394fe662c41a71e5d4f_l3.svg\" alt=\"\\Theta(nLogn)\" width=\"78\" height=\"18\" \/>.<br \/>\nTime complexity of Merge Sort is <img decoding=\"async\" class=\"ql-img-inline-formula quicklatex-auto-format\" title=\"Rendered by QuickLaTeX.com\" src=\"http:\/\/www.geeksforgeeks.org\/wp-content\/ql-cache\/quicklatex.com-7ace2f489b005394fe662c41a71e5d4f_l3.svg\" alt=\"\\Theta(nLogn)\" width=\"78\" height=\"18\" \/> in all 3 cases (worst, average and best) as merge sort always divides the array in two halves and take linear time to merge two halves.<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(n)<\/p>\n<p><strong>Algorithmic Paradigm: <\/strong>Divide and Conquer<\/p>\n<p><strong>Sorting In Place:<\/strong> No in a typical implementation<\/p>\n<p><strong>Stable:<\/strong> Yes<\/p>\n<p><strong>Applications of Merge Sort<\/strong><\/p>\n<ol>\n<li>Merge Sort is useful for sorting linked lists in O(nLogn) time.In case of linked lists the case is different mainly due to difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike array, in linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore merge operation of merge sort can be implemented without extra space for linked lists.In arrays, we can do random access as elements are continuous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in linked list. Quick Sort requires a lot of this kind of access. In linked list to access i\u2019th index, we have to travel each and every node from the head to i\u2019th node as we don\u2019t have continuous block of memory. Therefore, the overhead increases for quick sort. Merge sort accesses data sequentially and the need of random access is low.<\/li>\n<li>Inversion Count Problem<\/li>\n<li>Used in External Sorting<\/li>\n<\/ol>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Merge Sort &#8211; searching and sorting algorithm &#8211; Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,83481],"tags":[71272,71278,71285,71292,2380,70461,71121,70978,71131,70975,71123,71122,71129,70780,70465,71151,71287,70905,70497,71313,70271,70928,70894,70904,71304,70966,71216,70017,71230,71158,71295,70262,71262,71289,71274,71307,71276,71284,71165,71280,71288,71273,71286,70899,71270,71279,71282,70938,71290,71310,71275,71268,71297,71263,71296,71306,71281,71264,71301,71302,71300,71271,71277,70547,71312,71309,71305,71283,71267,71172,70046,71145,71303,71265,70977,71269,71266,71120,70016,70964,71308,71298,71162,71299,71291,70020,70652,70560,71293,70544,71294,71311],"class_list":["post-25089","post","type-post","status-publish","format-standard","hentry","category-coding","category-merge-sort","tag-algorithm-for-merge-sort","tag-algorithm-of-merge-sort","tag-analysis-of-merge-sort","tag-array-merge","tag-array-sort","tag-bubble-sort","tag-bubble-sort-algorithm","tag-bubble-sort-c","tag-bubble-sort-code","tag-bubble-sort-example","tag-bubble-sort-in-c","tag-bubble-sort-java","tag-bubble-sort-program","tag-bubblesort","tag-bucket-sort","tag-bucket-sort-algorithm","tag-c-program-for-merge-sort","tag-complexity-of-merge-sort","tag-counting-sort","tag-define-merge","tag-heap-sort","tag-heap-sort-algorithm","tag-heap-sort-program","tag-heapsort-java","tag-in-place-merge-sort","tag-insert-sort","tag-insertion-sort","tag-insertion-sort-algorithm","tag-insertion-sort-logic","tag-java-sort","tag-merge-array","tag-merge-sort","tag-merge-sort-algorithm","tag-merge-sort-algorithm-in-c","tag-merge-sort-algorithm-in-data-structure","tag-merge-sort-algorithm-in-java","tag-merge-sort-algorithm-with-example","tag-merge-sort-analysis","tag-merge-sort-c","tag-merge-sort-c-code","tag-merge-sort-c-program","tag-merge-sort-code","tag-merge-sort-code-in-c","tag-merge-sort-complexity","tag-merge-sort-example","tag-merge-sort-example-step-by-step","tag-merge-sort-explained","tag-merge-sort-in-c","tag-merge-sort-in-c-program","tag-merge-sort-in-cpp","tag-merge-sort-in-data-structure","tag-merge-sort-in-java","tag-merge-sort-in-python","tag-merge-sort-java","tag-merge-sort-java-code","tag-merge-sort-linked-list","tag-merge-sort-program","tag-merge-sort-program-in-c","tag-merge-sort-program-in-c-language","tag-merge-sort-program-in-c-with-explanation","tag-merge-sort-program-in-java","tag-merge-sort-pseudocode","tag-merge-sort-python","tag-merge-sort-time-complexity","tag-merge-sort-using-recursion","tag-merge-sort-vs-quicksort","tag-merge-sort-worst-case","tag-program-for-merge-sort","tag-quick-sort-algorithm","tag-quick-sort-program","tag-quicksort","tag-quicksort-c","tag-quicksort-code","tag-quicksort-example","tag-quicksort-java","tag-radix-sort","tag-radix-sort-algorithm","tag-selection-sort","tag-selection-sort-algorithm","tag-selection-sort-code","tag-sort-array","tag-sort-function","tag-sort-java","tag-sort-linked-list","tag-sort-unix","tag-sorting-algorithms","tag-sorting-algorithms-in-c","tag-space-complexity-of-merge-sort","tag-stable-sort","tag-time-complexity-of-merge-sort","tag-what-is-merge-sort","tag-worst-case-of-merge-sort"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25089","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25089"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25089\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25089"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25089"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25089"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}