Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I study python programming and try to sort data in descending order. #sort1 below is successfully sorted but I cannot understand why this happen. Also, data[i], data[data.index(mn)] = data[data.index(mn)], data[I] is suspicious point.

data = [-1.48,  4.96,  7.84, -4.27,  0.83,  0.31, -0.18,  3.57,  1.48,  5.34,
         9.12,  7.98, -0.75,  2.22, -1.16,  6.53, -5.38,  1.63, -2.85,  7.89,
        -5.96, -8.23,  8.76, -2.97,  4.57,  5.21,  9.43,  3.12,  6.52,  1.58 ]
#sort1

for i in range(30):
    mn = data[i]
    for j in data:
        if j < mn:
            mn = j
            data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
        else:
            pass
print('ascending order1:')
print(data)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...