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 bubble 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.
The problem settings are as follows. The explanation of the algorithm is omitted. Please refer to "Algorithm Picture Book".
Returns the columns sorted by the smallest number for a given number of columns. Example: 4, 3, 1, 2 → 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.
bubble_sort.py
data = [4, 3, 1, 2]
print("input :" + str(data))
data_len = len(data)
for k in range(0, data_len - 1):
i = data_len - 1
while(i - 1 >= k):
if data[i - 1] > data[i]:
temp_data = data[i - 1]
data[i - 1] = data[i]
data[i] = temp_data
else:
pass
i -= 1
print("output :" + str(data))
python
$ python bubble_sort.py
input :[4, 3, 1, 2]
output :[1, 2, 3, 4]
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