Merge sort is a sorting technique that is based on the divide and conquer method. It is one of the most respected algorithms, with a worst-case time complexity of O(n log n).
Merge sort divides the array into equal parts before combining them in a sorted fashion.
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1 − if it is only one element in the list it is already sorted, return. Step 2 − divide the list recursively into two halves until it can no more be divided. Step 3 − merge the smaller lists into new list in sorted order.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
procedure mergesort( var a as array ) if ( n == 1 ) return a var l1 as array = a[0] ... a[n/2] var l2 as array = a[n/2+1] ... a[n] l1 = mergesort( l1 ) l2 = mergesort( l2 ) return merge( l1, l2 ) end procedure procedure merge( var a as array, var b as array ) var c as array while ( a and b have elements ) if ( a[0] > b[0] ) add b[0] to the end of c remove b[0] from b else add a[0] to the end of c remove a[0] from a end if end while while ( a has elements ) add a[0] to the end of c remove a[0] from a end while while ( b has elements ) add b[0] to the end of c remove b[0] from b end while return c end procedure
0
This is a topic that is near to my heart…
Thank you! Where are your contact details though?
Heyy There. I found ypur blokg sing msn. This is a reeally welll written article.
I will maake ure too bookmark iit andd come back to read more oof your useful info.
Thanks for thhe post. I’ll certtainly return.
Apprecciate the recommendation. Lett me
trry it out.
Hi colleagues, how iis all, andd what you want to sayy concerning thnis post,
inn mmy vkew iits genuonely amazing in favopr off me.
It’s very effortless to find outt any topi on web
aas compared to textbooks, as I found thhis post aat this site.
Generaloly I do not lern ppost on blogs, however I wih too saay that this write-up ver
predssured mee tto cgeck outt and do it! Youur
writing taete haas beeen ssurprised me. Thanks, vsry great post.
Terdific work! Thaat is tthe kind oof infofmation that are meant to be shared arohnd the internet.
Shaqme oon Google foor noow not ositioning
this post upper! Coome on overr andd discuss with mmy site .
Thanms =)
This post is invaluable. Where can I find out more?