1
infile = open("array.txt", "r")
array = infile.readlines()
for i in range(len(array)):
array[i] = str(array[i])
array[i] = array[i].rstrip('\n')
#insertion sort
i = 0
while i <= (len(array) - 2):
if array[i] > array[i+1]:
temp = array[i+1]
j = i
while j >= 0 and array[j] > temp:
array[j+1] = array[j]
j = j - 1
array[j+1] = temp
i = i+1
print(array)
一些號碼是否正確......排序,而有些數字是不是:插入排序的代碼在Python不正確排序
original list: ['1534', '78675', '2345', '7861', '345', '8761', '1', '27456']
['1534', '2345', '78675', '7861', '345', '8761', '1', '27456']
['1534', '2345', '7861', '78675', '345', '8761', '1', '27456']
['1534', '2345', '345', '7861', '78675', '8761', '1', '27456']
['1', '1534', '2345', '345', '7861', '78675', '8761', '27456']
['1', '1534', '2345', '27456', '345', '7861', '78675', '8761']
['1', '1534', '2345', '27456', '345', '7861', '78675', '8761']
第2次工作正常,但在第3遍,「345 '沒有正確排序。誰能幫我?
編輯:如果我沒有從文本文件讀取數組,而是隻是定義數組,排序工作。這是爲什麼?
或做比較時保留字符串 – logic
我看到原來的列表轉換爲'INT()'...我還沒有聽說過這個詞的「字典式」前。你介意給我一個簡短的解釋嗎?我搜索了維基,但無法真正理解它......但除此之外,謝謝! – InvizTJ
它與「按字母順序排列」相似,只是它包含所有ASCII字符,而不僅僅是字符A-Z。 – Kevin