WC 01
WC 01
1. Sort on Top
We are going to compare the running times of 3 sorting algorithms: insertion sort, merge
sort, and python’s built-in sorted. For a given sequence, a, of size, n, we will note the time,
t, it takes to sort a using each of the algorithms. We will obtain values of t for various values
of n and plot them. We will then use the plot to estimate the size of n at which merge sort
becomes faster than insertion sort.
Task
Write a program that
• iterates a variable, n, over the values 10, 20, 30, 40, . . . , 500,
• for each n, generates a random sequence (list), a, of n integers,
• measures the time taken to sort each a by each of the following algorithms: insertion
sort, merge sort, and python’s built-in sorted,
• plots the time taken by each algorithm for each of the values of n.
Use the plot to estimate, n0 , the value of n at which merge sort becomes faster than insertion
sort.
Submission
You will submit an image file containing the plot and, overlaid on it, the string, n0 =?, where
“?” is replaced by your value of n0 . Also submit your py file.
Hint
• Use step with range to iterate over values of n.
• A random sequence of size n can be generated as
import random
a = list ( range ( n ) )
random . shuffle ( a )
• Here is a collection of timing functions in python. You may use any one.
• Insertion- and merge- sort are standard sorting algorithms. You may use third-party
implementations.
• Remember to make a copy of a for each sorting algorithm, so that each algorithm sorts
the same sequence of values.
• You may use the matplotlib module for plotting.
Page 2