Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into 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 a 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 the following C implementation for details.
MergeSort(arr[], l, r)
If r > l
The following diagram 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 into two halves till the size becomes 1. Once the size becomes 1, the merge processes come into action and start merging arrays back till the complete array is merged.
C++
C
Java
Python3
C#
Javascript
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Other Sorting Algorithms on GeeksforGeeks: 3-way Merge Sort, Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
Let the head by the first node of the linked list be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so the head node has to be changed if the data at the original head is not the smallest value in the linked list.
MergeSort(headRef)
C++
C
Java
Python3
C#
Javascript
Output:
Sorted Linked List is:
2 3 5 10 15 20
Time Complexity: O(n*log n)
Space Complexity: O(n*log n)}
Approach 2: This approach is simpler and uses log n space.
mergeSort():
merge(head1, head2):
Java
C#
Javascript
Output:
Sorted Linked List is:
2 3 5 7 10 20
Time Complexity: O(n*log n)
Space Complexity: O(log n)
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.
For example, the following doubly linked list should be changed to 24810
C++
C
Java
Python
C#
Javascript
Output:
Linked List after sorting
Forward Traversal using next pointer
3 4 5 10 20 30
Backward Traversal using prev pointer
30 20 10 5 4 3
81 videos|80 docs|33 tests
|
1. What is merge sort for linked lists? |
2. How does merge sort work for doubly linked lists? |
3. What is the complexity of merge sort for linked lists? |
4. Why is merge sort preferred for linked lists over other sorting algorithms? |
5. Can merge sort be used for sorting arrays as well? |
|
Explore Courses for Computer Science Engineering (CSE) exam
|