Python select sort algorithm implementation code

  • 2020-04-02 13:11:39
  • OfStack

1. The algorithm:
For a set of keywords {K1,K2... Kn}, first from K1,K2... ,Kn, choose the minimum value, if it is Kz, Kz and K1 exchange;
And then from K2, K3... , Kn, choose the minimum value Kz, and then swap Kz with K2.
In this way, choose and replace n-2 times. At the (n-1) time, choose the minimum value Kz from kn-1 and Kn and swap Kz with kn-1. Finally, what is left is the maximum value in the sequence.

2. Python selection sort code:


def selection_sort(list2):
    for i in range(0, len (list2)):
        min = i
        for j in range(i + 1, len(list2)):
            if list2[j] < list2[min]:
                min = j
        list2[i], list2[min] = list2[min], list2[i]  # swap

The results are: [2, 3, 4, 21, 33, 44, 45, 67]


Related articles: