$ mkdir ~/cs170/labs/lab17 $ cd ~/cs170/labs/lab17
Turn in your pseudo code at the beginning of class. Don't forget to put your name on it!
It has been a while, but we need to get back into the swing of things. Expect a breif quiz on recursion this Wednesday.
You all have been asking "Is there a binary sort?" Well, the idea behind binary search finds its way into two different algorithms. These are Merge Sort and Quick Sort. They both approach the problem the same way as all of our other recursive functions: Break the problem into smaller portions, and build the overal solution from those smaller pieces.
Merge sort is probably the closest to a "binary" sort as you will get. Merge sort simply splits the list into two halves, and recursively calls Merge sort on both halves. Onces it gets the two sorted halves, it simply merges the two together to form a sorted list.
Copy your sorting.py file from lab14 into this directory:
$ cd ~/cs170/labs/lab17/ $ cp ../lab14/sorting.py .
Create a function called merge_sort(a_list, start, end)
, which
takes a list of integers, as well as two integers representing the
beginning and end of the portion of the list to be sorted.
This function will not return anything. It will simply re-order the
elements of a_list in place. The algorithm was described in Chapter 2 of the
textbook. The Pseudo code is in Section 2.3.1.
Once you have your function written, try to figure out the Big-Oh class of Merge Sort. Write your estimation in the comments of your file somewhere near your Merge Sort function.
>>> my_list = [5, 4, 3, 2, 1] >>> merge_return_value = merge_sort(my_list, 0, len(my_list)) >>> print(merge_return_value) None >>> print(my_list) [1, 2, 3, 4, 5]
Once again, there is a more "pythonic" way to accomplish this algorithm. You can easily use list slicing in order to split the list into two halves. Your merge procedure then just takes two lists, and returns the merging of both of these lists.
Write a function called merge_sort_slice(a_list)
, which
performs merge sort using list slicing. This version of merge sort
should return a copy of a_list in sorted order. You will also need a new
merge_slice(list_1, list_2)
, which returns a new list
that represents the merging of list_1 and list_2.
When you have finished, create a tar file of your lab17
directory. To create a tar file, execute the following commands:
cd ~/cs170/labs tar czvf lab17.tgz lab17/
To submit your activity, go to cseval.roanoke.edu. You should
see an available assignment called Lab Assignment 17
.
Make sure you include a header listing the authors of the file.