2 回答

TA貢獻1856條經(jīng)驗 獲得超5個贊
這是插入排序https://en.wikipedia.org/wiki/Insertion_sort
您可以將其想象為對項目的流式列表進行排序:
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]
更新
插入排序背后的直覺是,每次獲得新項目時,您都會更新先前排序的列表。因此,您無需擔(dān)心未來項目的排序位置。
由于時間之前的數(shù)據(jù)i是排序的,那么在找到第一個交換之后,所有的項目都會交換,直到它再次到達時間i。
現(xiàn)在,交換命令的問題:
data[i], data[data.index(mn)] = data[data.index(mn)], data[i]
實際上,這個交換命令會忽略未來的交換(何時data.index(mn)大于當(dāng)前時間i)。但是,由于它在時間i大于時起作用data.index(mn),因此對于插入排序來說已經(jīng)足夠了。這是一個例子:
# 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)

TA貢獻1871條經(jīng)驗 獲得超8個贊
您的代碼中有 2 個錯誤:
最好在循環(huán)中執(zhí)行for i in range(len(data)),因此如果變量數(shù)據(jù)的大小發(fā)生變化,您的代碼將起作用。
您的代碼按降序?qū)?shù)據(jù)進行排序,因此您應(yīng)該打印:print('descending order1:')
現(xiàn)在,讓我們談?wù)勊惴ú糠帧嶋H上,您的代碼是排序算法冒泡排序的實現(xiàn),也稱為下沉排序。該算法重復(fù)遍歷列表并比較相鄰元素。如果它們的順序錯誤(即如果第一個元素低于第二個),它將交換相鄰元素。它這樣做直到列表被排序(按降序排列)。你可以在這里得到更多的了解
代碼data[i], data[data.index(mn)] = data[data.index(mn)], data[i]只是交換部分。這是一種交換元素的 Pythonic 方式。例如:
a = 5
b = 15
a, b = b, a # swap 'elegantly a and b
print(a) # display 15
print(b) # display 5
代碼評論:
for i in range(30): # first cursor: steps through the indexes of the list
mn = data[i] # assigns the data at index i to the variable mn
for j in data: # second cursor: steps through the data of the list
if j < mn: # compares adjacent elements
mn = j
data[i], data[data.index(mn)] = data[data.index(mn)], data[i] # swap adjacent elements
else: # if the first data superior to the second, don't do anything
pass
添加回答
舉報