How to Implement Selection Sort in Python


In this example, we will learn how to sort numbers in Python.

Algorithm

The algorithm of selection sort is very simple:

Initially find the smallest (or largest) element in the sequence, put it at the beginning of the sequence as the sorted sequence.  Then, continue to find the smallest (or largest) element from the remaining unsorted elements, put it at the end of the sorted sequence. And repeat the operation until all the elements are sorted.

Source Code

#!/usr/bin/python
#!/usr/bin/python
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
    N = 10
    # input data
    print('please input 10 numbers')
    l = []
    for i in range(1,N+1):
        l.append(int(input('please input: ')))

    #for loop from the first element to last element
    for i in range(N - 1):
        min = i
        # min is the subscript position of the current smallest element from the (i+1)th element to the last element
        for j in range(i + 1, N):
            if l[min] > l[j]:
                # Exchange min if the subsequent element is smaller than the current smallest element
                min = j
        # In this loop, the smallest element position is exchanged with min
        l[i], l[min] = l[min], l[i]
        
    # output sorted results
    print("\nSorted Results:")
    for i in range(N):
        print(l[i])

Output:

please input 10 numbers
please input: 3
please input: 6
please input: 33
please input: 78
please input: 42
please input: 11
please input: 5
please input: 92
please input: 34
please input: 8

Sorted Results:
3
5
6
8
11
33
34
42
78
92
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement