Selection Sort

In [2]:
%pprint
Pretty printing has been turned OFF
In [8]:
from random import sample
nums = sample(range(1000), k=20)
nums
Out[8]:
[570, 674, 407, 547, 23, 733, 133, 507, 346, 542, 215, 351, 360, 811, 402, 954, 894, 418, 71, 400]
In [17]:
num_comparisons = 0
num_swaps = 0

def selection_sort(alist):
    global num_comparisons, num_swaps
    
    for fillslot in range(len(alist)-1, 0, -1):
        position_of_max = 0
        for location in range(1, fillslot+1):
            num_comparisons += 1
            if alist[location] > alist[position_of_max]:
                position_of_max = location
                
        num_swaps += 1
        alist[fillslot], alist[position_of_max] = alist[position_of_max], alist[fillslot]
In [18]:
selection_sort(nums)
In [19]:
nums
Out[19]:
[23, 71, 133, 215, 346, 351, 360, 400, 402, 407, 418, 507, 542, 547, 570, 674, 733, 811, 894, 954]
In [20]:
print(num_comparisons, num_swaps)
190 19