# Merge Sort

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)

## WHAT IS IT?

This model is a visual demonstration of a standard sort algorithm called merge sort. The algorithm reorders, or permutes, n numbers into ascending order. This is accomplished by dividing the numbers into groups and then merging smaller groups to form larger groups. Order is maintained as the lists are merged so when the algorithm finishes there is only one sorted list containing all n items.

Note that it is possible to express merge sort in NetLogo much more concisely than is done in this model. Since this model aims to demonstrate the sort algorithm visually, the code is more complex than would be needed if the model only needed to sort the numbers.

## HOW IT WORKS

We start out with as many independent groups as we have elements. As the algorithm progresses through the list, it merges each adjacent pair of groups; thus, after each pass, the number of groups is halved.

To merge two groups:

- Compare the first elements of the two groups to each other
- Place the smallest/largest element (depending on the increasing-order? switch) of the two in a third group
- Remove that element from its source group
- Repeat until one of the source groups is empty
- Place all of the remaining elements from the non-empty source group onto the end of the third group
- Substitute, in place, the third group for the two source groups

We do this merge repeatedly for each set of two groups until there is only one group left. This final group is the original set of numbers in sorted order.

The number of steps required to sort n items using this algorithm is the ceiling of logarithm (base 2) of n. Each step requires at most n comparisons between the numbers. Therefore, the time it takes for the algorithm to run is about n log n. Computer scientists often write this as O(n log n) where n is how many numbers are to be sorted.

## HOW TO USE IT

Change the value of the NUMBER-OF-ELEMENTS slider to modify how many numbers to sort.

Pressing SETUP creates NUMBER-OF-ELEMENTS random values to be sorted.

STEP (1 ITEM) merges one number into its new group.

STEP (1 ROW) does one full round of group merges.

## THINGS TO NOTICE

Groups are represented by color. Numbers in the same group have the same color. When two groups merge, the numbers take the color of the smallest/largest element in the new group. Can you predict what would be the final color of all elements before starting?

Would merging more than two groups at a time lead to the elements getting sorted in fewer steps? Would this change make the algorithm any faster?

## THINGS TO TRY

We stated above that the algorithm will take at most a constant factor times n log n time to execute. Can you figure out why the constant factor is needed to make this statement accurate?

## EXTENDING THE MODEL

Can you make the elements draw their paths across the view?

There are many different sorting algorithms. You can find a few described at http://en.wikipedia.org/wiki/Sorting_algorithm. Try implementing the different sorts in NetLogo and use BehaviorSpace to compare them. Do different sorts perform better with different input sets (uniformly random, nearly sorted, reverse sorted, etc.)?

## NETLOGO FEATURES

This model uses lists extensively.

Note that NetLogo includes SORT and SORT-BY primitives; normally, you would just use one of these, rather than implementing a sort algorithm yourself. SORT arranges items in ascending order; SORT-BY lets you specify how items are to be ordered.

## HOW TO CITE

If you mention this model in a publication, we ask that you include these citations for the model itself and for the NetLogo software:

- Wilensky, U. (2005). NetLogo Merge Sort model. http://ccl.northwestern.edu/netlogo/models/MergeSort. Center for Connected Learning and Computer-Based Modeling, Northwestern Institute on Complex Systems, Northwestern University, Evanston, IL.
- Wilensky, U. (1999). NetLogo. http://ccl.northwestern.edu/netlogo/. Center for Connected Learning and Computer-Based Modeling, Northwestern Institute on Complex Systems, Northwestern University, Evanston, IL.

## COPYRIGHT AND LICENSE

Copyright 2005 Uri Wilensky.

This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

Commercial licenses are also available. To inquire about commercial licenses, please contact Uri Wilensky at uri@northwestern.edu.

## Comments and Questions

breed [ mergers merger ] breed [ elements element ] elements-own [ value ] mergers-own [ merge-group ] globals [ group-count ;; Number of groups (lists) of elements group-list ;; List of lists of elements step-number ;; Number of complete merge steps finished current-loc ;; Group position of next element to be drawn, used by single-sort current-group ;; Group number of next element to be drawn, used by single-sort current-count ;; Element number of next element to be drawn, used by single-sort ] ;;;;;;;;;;;;;;;;;;;;;; ;; Setup Procedures ;; ;;;;;;;;;;;;;;;;;;;;;; to setup ca set current-count 1 set current-loc 0 set current-group 0 set step-number 0 set group-list [] set group-count number-of-elements setup-elements end to setup-elements set-default-shape turtles "circle" create-elements number-of-elements [ set size 5 set value (random (4 * number-of-elements)) ;; (list self) creates a list with its sole item being the turtle itself set group-list lput (list self) group-list ] draw end ;;;;;;;;;;;;;;;;;;;;;;;; ;; Runtime Procedures ;; ;;;;;;;;;;;;;;;;;;;;;;;; ;; Do one set of group merges. That is, have each pair of neighboring groups merge. to step-row ;; Finish displaying current step if need be if (current-count > 1) [ draw set current-count 1 set current-loc 0 set current-group 0 stop ] ;; Stop if the first group contains all elements which means all elements ;; have been sorted. if (length (item 0 group-list) = number-of-elements) [ stop ] set step-number (step-number + 1) combine-groups draw end ;;;;;;;;;;;;;;;;;;;;;;;; ;; Merging Procedures ;; ;;;;;;;;;;;;;;;;;;;;;;;; to combine-groups let num 0 ;; Create a merger for every two groups ;; Each merger will combine two groups create-mergers (group-count / 2) [ set merge-group num set num (num + 2) ] ask mergers [ merge (item merge-group group-list) (item (merge-group + 1) group-list) merge-group die ] ;; Remove empty groups (-1's) from our list set group-list remove -1 group-list set group-count length group-list end ;; Merge lists 1 and 2 into one list, maintaining order to merge [ list1 list2 location ] ;; mergers procedure let new-list [] ;; Sort the lists into new-list until either list1 or list2 is empty. ;; The groups are merged into increasing/decreasing order depending on ;; whether the increasing-order switch in on/off. let item1 0 let item2 0 while [(not empty? list1) and (not empty? list2)] [ set item1 item 0 list1 set item2 item 0 list2 ifelse ( [value] of item1 < [value] of item2 ) [ set new-list lput item1 new-list set list1 but-first list1 ] [ set new-list lput item2 new-list set list2 but-first list2 ] ] ;; One of the lists is always going to be non-empty after the above loop. ;; Put the remainder of the non-empty list into new-list. ifelse (empty? list1) [ set new-list sentence new-list list2 ] [ set new-list sentence new-list list1 ] ;; Copy the new-list into the appropriate location in group-list. ;; [(a+b) b c d] becomes [(a+b) -1 c d] ;; The -1's will be removed once the entire step is complete. ;; We do this instead of removing it here to keep order and length intact. set group-list (replace-item location group-list new-list) set group-list (replace-item (location + 1) group-list -1) end ;;;;;;;;;;;;;;;;;;;;;;;; ;; Display Procedures ;; ;;;;;;;;;;;;;;;;;;;;;;;; to step-item ;; If we have finished this round of sorting, reset our values if (current-count > number-of-elements) [ set current-count 1 set current-loc 0 set current-group 0 ] ;; Do a round of sorting before we display if necessary if (current-count = 1) [ ;; Stop if the first group contains all elements which means all elements ;; have been sorted. if (length (item 0 group-list) = number-of-elements) [stop] set step-number (step-number + 1) combine-groups ;; To display the step number. ask patch (min-pxcor + 2) (max-pycor - 5 - (step-number * 10)) [set plabel-color green set plabel step-number] ] ;; Display the current element with its new position and color. let tcolor [color] of first (item current-group group-list) ask (item current-loc (item current-group group-list)) [ set pcolor color set color tcolor set ycor (max-pycor - 5 - (10 * step-number)) set xcor (min-pxcor + (current-count * ((2 * max-pxcor) / (number-of-elements + 1)))) ask patch-at 0 4 [set plabel-color white set plabel [value] of myself] ] ;; Update information about which turtle to display next set current-count (current-count + 1) ifelse(length (item current-group group-list) = (current-loc + 1)) [ set current-loc 0 set current-group (current-group + 1) ] [ set current-loc (current-loc + 1) ] end ;; Move the turtles to their appropriate locations to draw let list-loc 0 let element-num 1 ;; Evenly space the elements across the view let separation ((2 * max-pxcor) / (number-of-elements + 1)) ;; To display the step number. ask patch (min-pxcor + 2) (max-pycor - 5 - (step-number * 10)) [set plabel-color green set plabel step-number] while [list-loc < group-count] [ let current-list item list-loc group-list let tcolor [color] of first current-list while [not empty? current-list] [ ask (item 0 current-list) [ ;; To keep track of what group an element belonged to before the current step, ;; we leave the color and display the value at it's previous place. if (step-number != 0) [ set pcolor color] set color tcolor set ycor (max-pycor - 5 - (10 * step-number)) set xcor (min-pxcor + (element-num * separation)) ask patch-at 0 4 [set plabel-color white set plabel [value] of myself] ] set element-num (element-num + 1) set current-list but-first current-list ] set list-loc (list-loc + 1) ] end ; Copyright 2005 Uri Wilensky. ; See Info tab for full copyright and license.

There are 10 versions of this model.

## Attached files

File | Type | Description | Last updated | |
---|---|---|---|---|

Merge Sort.png | preview | Preview for 'Merge Sort' | almost 10 years ago, by Uri Wilensky | Download |

This model does not have any ancestors.

This model does not have any descendants.