Introduction To Computation and Programming Using Python, Revised - Guttag, John v..149
Introduction To Computation and Programming Using Python, Revised - Guttag, John v..149
Base case: At the start of the first iteration, the prefix is empty, i.e., the
suffix is the entire list. The invariant is (trivially) true.
Induction step: At each step of the algorithm, we move one element from
the suffix to the prefix. We do this by appending a minimum element of
the suffix to the end of the prefix. Because the invariant held before we
moved the element, we know that after we append the element the prefix
is still sorted. We also know that since we removed the smallest element
in the suffix, no element in the prefix is larger than the smallest element
in the suffix.
When the loop is exited, the prefix includes the entire list, and the suffix
is empty. Therefore, the entire list is now sorted in ascending order.
def selSort(L):
"""Assumes that L is a list of elements that can be
compared using >.
Sorts L in ascending order"""
suffixStart = 0
while suffixStart != len(L):
#look at each element in suffix
for i in range(suffixStart, len(L)):
if L[i] < L[suffixStart]:
#swap position of elements
L[suffixStart], L[i] = L[i], L[suffixStart]
suffixStart += 1