Mergesort is yet another divide and conquer method of sorting.
It works by partitioning the list into two halfs, then applying merge sort
to each half. This process continues until sublists contain a single
element. The actual sorting occurs by a merge process that merges sublists as
they return sorted. Although, mergeSort can be used in sorting arrays,
lets consider it in the context of a linked list implementation.
The Algorithm has the following recursive structure:
Node mergeSort (Node head, int size) {
if head is null or size 1
return head
else {
create left and right sublists
left = mergeSort(left, leftSize)
right = mergeSort(right,rightSize)
return merge(left,right)
}
}
Keep in mind that this is just an algorithm, you can't just type it in and expect it work. There are a number things that may not be obvious to to you:
head --> 11 --> 9 --> 13 --> 10 --> 12 --> After splitting: first --> 11 --> 9 --> second --> 13 --> 10 --> 12 -->
Note that head will still be referencing the node with 11, but we don't care.
mergeSort(head-->11-->9-->13-->10-->12 , size=5) {return -->9-->10-->11-->12-->13} / \ / \ mergeSort(head-->11-->9,size=2) mergeSort(head-->13-->10-->12,size=3) {return -->9-->11-->} {return -->10-->12-->13-->} / \ / \ / \ / \ mergeSort(head-->11, mergeSort(head-->9, / \ size =1) size =1) / \ {return -->11} {return -->9} / \ mergeSort(head-->13, mergeSort(head-->10-->12, size =1) size =2) {return -->13} {return -->10-->12} / \ / \ / \ / \ mergeSort(head-->10, mergeSort(head-->12, size =1) size =1) {return -->10} {return -->12}