This is the selection sort algorithm:
L
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):
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.
This is the bubble sort algorithm:
L
Here's a video of the bubble sort algorithm (click to play):
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.
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):
See if you can add insertionSort()
to our sorts.py
file.
Include some test code at the bottom of sorts.py
!