Python 中的插入排序代码排序不正确
Insertion Sort Code in Python not sorting correctly
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)
有些号码排序正确...而有些号码不正确:
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”排序不正确。谁能帮帮我?
编辑:如果我没有从文本文件中读取数组,而只是定义了数组,则排序有效。为什么会这样?
这可能是因为 "345" > "2345"
为真,因为字符串“345”按字典顺序排在“2345”之后。如果您想要数字排序,请尝试用数字而不是字符串填充您的原始列表。
array = [1534, 78675, 2345, 7861, 345, 8761, 1, 27456]
i = 0
while i <= (len(array) - 2):
#etc
结果:
[1, 345, 1534, 2345, 7861, 8761, 27456, 78675]
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)
有些号码排序正确...而有些号码不正确:
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”排序不正确。谁能帮帮我?
编辑:如果我没有从文本文件中读取数组,而只是定义了数组,则排序有效。为什么会这样?
这可能是因为 "345" > "2345"
为真,因为字符串“345”按字典顺序排在“2345”之后。如果您想要数字排序,请尝试用数字而不是字符串填充您的原始列表。
array = [1534, 78675, 2345, 7861, 345, 8761, 1, 27456]
i = 0
while i <= (len(array) - 2):
#etc
结果:
[1, 345, 1534, 2345, 7861, 8761, 27456, 78675]