# 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
l = []
for i in range(1,N+1):

#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

Sorted Results:
3
5
6
8
11
33
34
42
78
92
``````
Subscribe
Notify of 