This is insertion sort https://en.wikipedia.org/wiki/Insertion_sort
You can imagine it as if sorting a streamed list of items:
for i in range(30): # for each item streamed here
mn = data[i] # take the new item (if exists new item)
for j in data: # find its place in the sorted data, and insert it there:
if j < mn: # if found its place, insert it here
mn = j
data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
UPDATE
The intuition behind the insertion sort is that you update the previously sorted list each time you get to a new item. So, you don't need to worry about the sorting position of future items.
Since the data before time i
is sorted, then after the finding the first swap all items will swap until it reaches the time i
again.
Now, the problem with the swapping command:
data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
This swapping command, in fact, ignores future swappings (when data.index(mn)
is larger than the current time i
). However, since it works when time i
is larger than data.index(mn)
, that is enough for insertion sort. This is an example of:
# two attempts to swapping x and y:
data = ['x', 'y']
# ignored (target of swap is at time i, found position in future!):
i = 0; mn = 'y' # data.index(mn) == 1
data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
print('ignored swap', data)
# success (target of swap is at time i, found position in past (before i)):
i = 1; mn = 'x' # data.index(mn) == 0
data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
print('success swap', data)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…