View
236
Download
2
Embed Size (px)
DESCRIPTION
Citation preview
Merge sort
Merge sort has a secret sauce - it’s how you mix lists
2 5 7 1 3 8Sorted list A Sorted list B
Merged List
Merge sort
2 5 7 1 3 8Sorted list A Sorted list B
Merged ListTo merge two sorted lists begin at the
beginning of each
Merge sort secret sauce
2 5 7 1 3 8Sorted list A Sorted list B
Merged List
You have two markers (red)for for each list.
Merge sort secret sauce
2 5 7 1 3 8Sorted list A Sorted list B
Merged ListThe next item in the merged list is the lower
of the two
Merge sort secret sauce
2 5 7 1 3 8
1
Sorted list A Sorted list B
Merged ListThe next item in the merged list is the lower
of the two
Merge sort secret sauce
2 5 7 1 3 8
1 2
Sorted list A Sorted list B
Merged ListIf you use a marker you move it forward and
try again
Merge sort secret sauce
2 5 7 1 3 8
1 2 3
Sorted list A Sorted list B
Merged ListThe next item in the merged list is the lower
of the two
Merge sort secret sauce
2 5 7 1 3 8
1 2 3 5
Sorted list A Sorted list B
Merged List
Merge sort secret sauce
2 5 7 1 3 8
1 2 3 5 7
Sorted list A Sorted list B
Merged List
Merge sort secret sauce
2 5 7 1 3 8
1 2 3 5 7 8
Sorted list A Sorted list B
Merged ListWhen one list is used you can just use up all of
the other
Merge sort secret sauce
2 5 1 3 4 7 8
1 2 3 5 7 8
Sorted list A Sorted list B
Merged ListList don’t even have to be the same length to
work!
Merge sort secret sauce
Once you know how to merge
two sorted lists the rest is easy
Begin with unsorted list
Split into two
Split each list into two again
Split each list into two again, and again
Split each list into two again, and again
Until each list has one item in it
Each one item list is ‘sorted’
Now move back and look at the pairs
Merge the pairs as first described...
... to make sorted pairs
Now merge pairs lists keeping them sorted
Merge pairs of lists together...
Merge pairs of lists together...
Finally we get back to the first two lists...
Which we merge
Leaving the original list sorted
Your done!
2 5 1 3 8 7 4
1 2 3 5 7 8
Sorted list A Sorted list B
Merge sort secret sauce
Merging lists takes as long as the list (order(N))
You do this log(N) timesMaking algorithm Order (N log(N))
2 5 1 3 4 7 8
1 2 3 4 5 7
Sorted list A Sorted list B
Merge sort secret sauce
Merging lists takes as long as the list (order(N))
You do this log(N) timesMaking algorithm Order (N log(N))
Pity you need extra space to ‘merge’ into otherwise it would be pretty neet