简体   繁体   English

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)

Some numbers are sorted correctly... while some numbers are not: 一些数字正确排序...而有些数字则不是:

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']

The first 2 passes worked correctly, but in the 3rd pass, '345' wasn't sorted correctly. 前两遍正确运行,但在第三遍中,“ 345”未正确排序。 Can anyone help me? 谁能帮我?

EDIT: If I didn't read an array from a text file, and instead just defined array, the sorting worked. 编辑:如果我没有从文本文件中读取数组,而是仅定义了数组,则排序有效。 Why is this so? 为什么会这样呢?

This is probably because "345" > "2345" is True, because the string "345" comes lexicographically after "2345". 这可能是因为"345" > "2345"为True,因为字符串“ 345”在字典上位于“ 2345”之后。 If you want numeric sorting, try filling your original list with numbers instead of strings. 如果要进行数字排序,请尝试使用数字而不是字符串填充原始列表。

array = [1534, 78675, 2345, 7861, 345, 8761, 1, 27456]
i = 0
while i <= (len(array) - 2):
    #etc

Result: 结果:

[1, 345, 1534, 2345, 7861, 8761, 27456, 78675]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM