I've been studying python and algorithms, so I implemented selection sort.
Create a random list Example: [1,3,0,4,2]
Find the smallest value in the operation target list Example: [1,3,0,4,2] → 0 is the minimum
Replace the leftmost with 0, and 0 completes the operation.
[1,3,0,4,2]→[0,3,1,4,2]
-Next is the second from the left, then the third ... and so on, and repeat steps 2 and 3-
[1,3,0,4,2] [0,3,1,4,2] [0,1,3,4,2] [0,1,2,4,3] [0,1,2,3,4]
It seems that the process of ... is called selection sort.
select_sort.py
import random
#Enter the number of values to prepare
numbers = 10
#Create a list to store checked values
pop_list = []
#Random number creation
num_list = list(range(numbers))
random.shuffle(num_list)
def _select_min(num_list, pos):
_min = None
_left = num_list[pos]
_pos = 0
for i in range(pos, len(num_list)):
if _min == None or _min > num_list[i]:
_min = num_list[i]
_pos = i
num_list[pos] = _min
num_list[_pos] = _left
return(num_list)
#Main processing
print("START : ",num_list)
for i in range(len(num_list)):
num_list = _select_min(num_list, i)
print("GOAL : ",num_list)
Recommended Posts