Week 9, Wednesday: Sorting/Analysis of Algorithms



selection sort

This is the selection sort algorithm:

It is called selection sort because each time you are selecting the smallest number from the remaining unsorted elements.

I assume you understand the "find the smallest number in a list" part, but here it is:

ismall = 0               # index of first element in list
for i in range(len(L)):
  if L[i] < L[ismall]:
    ismall = i           # found a smaller item, so save position

# after the for loop, ismall should be the index of the 
# smallest item in the list
print "smallest is ", L[ismall]

The selection sort uses the above code, but not just for position 0. A second outer for loop is needed to run the above code for all values from 0 to the last index of the list.

Here is a video of the selection sort algorithm (click to play):

Selection Sort

See if you can add selectionSort() to our sorts.py file of sorts. Include some test code at the bottom of sorts.py to make sure your selectionSort() function is working properly.

bubble sort

This is the bubble sort algorithm:

Here's a video of the bubble sort algorithm (click to play):

Bubble Sort

See if you can add bubbleSort() to our sorts.py file. Include some test code at the bottom of sorts.py to make sure your bubbleSort() function is working properly.

insertion sort

This is the insertion sort algorithm:

Notice that, for each index, all items to the left are in order, and you are inserting the next item into the correct spot.

Here is a video of the insertion sort algorithm (click to play):

Insertion Sort

See if you can add insertionSort() to our sorts.py file. Include some test code at the bottom of sorts.py!