Sorting is a classic problem in computer science. In this program, you’ll implement a sorting algorithm called insertion sort. This sort operates in-place, which means that it moves elements around within the input list, rather than creating a new list that’s sorted.
The basic idea behind insertion sort is to notice that in the final sorted list:
…and so on.
With this insight in hand, we can sort using the following algorithm:
for each element of the list, find the smallest thing in the
rest of the list, then swap it into its correct
position. For example, consider sorting the list 3 4 1 2
.
In each step of the following, the current element under consideration
has a -
below it, and the smallest element (with which it
will be swapped) has a *
below it.
3 4 1 2 # find the smallest element among [3, 4, 1, 2]
- * # swap the 3 and the 1
1 4 3 2 # find the smallest element among [4, 3, 2]
- * # swap the 4 and the 2
1 2 3 4 # find the smallest among [3, 4]
* # 3 is both the current and the smallest
- # "swap" 3 with itself - it doesn't move
1 2 3 4 # the smallest among [4] is trivially 4, so we're done
-
To implement this, you’ll write two helper functions
(swap
and min_index
) and the main sorting
routine (isort
). Details of these functions are provided in
their specifications in the skeleton code.
For the main program, which is not tested by the unit tests, your program should read numbers from command line arguments and print them in sorted order, as in the following sample run:
>>> %Run P20_sort.py 3 4 1 2
[1, 2, 3, 4]
Write an algorithm to return the index of the first occurrence of a value v in a list L.
Pseudocode:
find(v, L):
for each element in L:
if the element is equal to v:
return the index of v
return -1
[This is the same as one of the extra practice problems from L19]. Write an algorithm that returns the index of the first occurrence of of a value v in a sorted list L, in such a way that you index into the list less than len(sorted_lst) times. This means a brute-force approach of checking all elements won’t work. To avoid this, you’ll need to think of a way to take advantage of the fact that the list is sorted.
Write an algorithm that takes a list L and returns a new list containing the same elements, but arranged in sorted (increasing) order
Write an algorithm that takes a list L and sorts its contents in place using a different algorithm from the one above. This means that, as above, the contents of the given list are rearranged without being copied into a new list.