Presentation is loading. Please wait.

Presentation is loading. Please wait.

By Brian Ahmann, Jared Hoffman, and Andy Miller

Similar presentations


Presentation on theme: "By Brian Ahmann, Jared Hoffman, and Andy Miller"— Presentation transcript:

1 By Brian Ahmann, Jared Hoffman, and Andy Miller
Merge Sort By Brian Ahmann, Jared Hoffman, and Andy Miller

2 Overview Merge sort is a fast, advanced sorting algorithm
Commonly implemented recursively (space issues) Much faster than insertion sort or selection sort (usually) Merge sort is stable: elements with the same value stay in their original order A merge sort has time efficiency O(n logn) for nearly all initial conditions The basic merge sort algorithm is easy to understand …but it can be difficult to implement

3 The Big Idea If a list has 0 or 1 element, then it is sorted. (Base Case) To sort a larger list: Break the list into two halves. Sort each half. (Recursion) Merge the sorted halves.

4 The recursion merge_sort(list a) { if(length of a <= 1) a is sorted else { list left = left half of a list right = right half of a merge_sort(left) merge_sort(right) merge(left, right) }

5 Activity We need 4 volunteers
Come to the front of class to be merge sorted! Put yourselves in a random order We will sort you by LAST NAME We are in control of the program, and will say when to move

6 Activity Come to the front of class to be merge sorted!
Now, we need 8 volunteers! You will do the same thing Come to the front of class to be merge sorted! Put yourselves in a random order We will sort you by LAST NAME We are in control of the program, and will say when to move

7 Merging By far the hardest part of the implementation of a merge sort algorithm is merging the two sorted sub-lists Go through each sub-list, and the lower number at the “current index” of each sub- list is added to the main list. LEFT RIGHT SORTED [1, 2, 5] [3, 4, 6] [1, _, _, _, _, _] [1, 2, 5] [3, 4, 6] [1, 2, _, _, _, _] [1, 2, 5] [3, 4, 6] [1, 2, 3, _, _, _] [1, 2, 5] [3, 4, 6] [1, 2, 3, 4, _, _] [1, 2, 5] [3, 4, 6] [1, 2, 3, 4, 5, _] [1, 2, 5] _ [3, 4, 6] [1, 2, 3, 4, 5, 6]

8 Merging merge(list left, list right) { sorted = [] left_index, right_index = 0 //Current index in left and right list while(in range of left AND right) { get the current element from each list add the lower of the two to the sorted list increase the index of the list the low element came from } add any leftover elements to the sorted list return sorted

9 Parallelism and Merge sort

10 Sources http://www.stackoverflow.com
g/mergeSort.htm


Download ppt "By Brian Ahmann, Jared Hoffman, and Andy Miller"

Similar presentations


Ads by Google