Data-Structures-with-Go/merge-sort
2018-12-06 14:02:05 +03:00
..
resources update readme 2017-10-26 22:21:57 +03:00
merge-sort_test.go [test] added unit test for merge-sort 2018-12-06 14:02:05 +03:00
merge-sort.go [fix] code format for merge-sort 2018-12-06 14:01:49 +03:00
README.md update readme 2017-10-26 22:29:49 +03:00

Merge Sort Source

What It Is

What It Is

Like QuickSort, MergeSort 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. The merge() function 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

Preview Thumbnail

MergeSort(arr[], l, r)

  • If r > l
    1. Find the middle point to divide the array into two halves:
      middle m = (l+r)/2
    1. Call mergeSort for first half:
      Call mergeSort(arr, l, m)
    1. Call mergeSort for second half: Call mergeSort(arr, m+1, r)
    1. Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r)

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

Preview Thumbnail

  • Input: {12, 11, 13, 5, 6, 7}
  • Output: Given array is 12 11 13 5 6 7
  • Output: Sorted array is 5 6 7 11 12 13

Algorithm Complexity

Complexity Notation
Time Complexity O(n log n)