In this article, I would like to introduce an implementation example in Python 3 about the algorithm that I learned by reading "Algorithm Picture Book". The algorithm this time is selection sort. The writer is an amateur. I would appreciate it if you could tell me various things.
I'm not familiar with Python2, but I only know that I'm using Python3 (Is it Python3.6.0?). Therefore, the title of the article is Python3.
I will only briefly explain the problem setting and approach.
Returns the columns sorted by the smallest number for a given number of columns. Example: 4, 3, 1, 2 → 1, 2, 3, 4
Determine the values in order from the beginning. Find the minimum value from the undetermined number and bring it to the front (first side) by swapping. See "Algorithm Picture Book" for details.
Example: Notation of fixed numbers enclosed in [] 4, 3, 1, 2 → [1], 3, 4, 2 → [1], [2], 4, 3 → [1], [2], [3], 4
The implemented code is shown below. The list assigned to the variable data first is the column of the number to be processed. Also, I implemented it without using min in the list.
selection_sort.py
data = [4, 3, 1, 2]
print("input :" + str(data))
data_len = len(data)
for k in range(0, data_len - 1):
min_index = k
min_data = data[k]
for i in range(k + 1, data_len):
if data[i] < min_data:
min_index = i
min_data = data[i]
else:
pass
data[min_index] = data[k]
data[k] = min_data
print("output :" + str(data))
python
$ python selection_sort.py
input :[4, 3, 1, 2]
output :[1, 2, 3, 4]
I posted it for the first time as a practice to post the code I wrote. If you have any questions, please point out and ask questions. Especially if there are any improvements in how to write the code, I think it will be useful for studying.
Recommended Posts