Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Merge sort
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Top-down implementation using lists === [[Pseudocode]] for top-down merge sort algorithm which recursively divides the input list into smaller sublists until the sublists are trivially sorted, and then merges the sublists while returning up the call chain. '''function''' merge_sort(''list'' m) '''is''' // ''Base case. A list of zero or one elements is sorted, by definition.'' '''if''' length of m β€ 1 '''then''' '''return''' m // ''Recursive case. First, divide the list into equal-sized sublists'' // ''consisting of the first half and second half of the list.'' // ''This assumes lists start at index 0.'' '''var''' left := empty list '''var''' right := empty list '''for each''' x '''with index''' i '''in''' m '''do''' '''if''' i < (length of m)/2 '''then''' add x to left '''else''' add x to right // ''Recursively sort both sublists.'' left := merge_sort(left) right := merge_sort(right) // Then merge the now-sorted sublists. '''return''' merge(left, right) In this example, the {{mono|merge}} function merges the left and right sublists. '''function''' merge(left, right) '''is''' '''var''' result := empty list '''while''' left is not empty '''and''' right is not empty '''do''' '''if''' first(left) β€ first(right) '''then''' append first(left) to result left := rest(left) '''else''' append first(right) to result right := rest(right) // ''Either left or right may have elements left; consume them.'' // ''(Only one of the following loops will actually be entered.)'' '''while''' left is not empty '''do''' append first(left) to result left := rest(left) '''while''' right is not empty '''do''' append first(right) to result right := rest(right) '''return''' result
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)