气泡排序未按正确顺序输出(浮动)

时间:2019-05-07 17:26:34

标签: python python-3.x sorting bubble-sort

似乎找不到任何有关此的信息,因为我无法真正正确地说出它。基本上,当我对列表进行冒泡排序时,从负数到最低负数,然后读入正数,可以说它是[1.6397,-2.0215,-0.4933,,-3.4167],它将排序为[-0.4933,-2.0215,-3.4167 ,1.6397]

通过算法是

    def bubbleSort(array):
        n=len(array)
         for i in range(n):
            for j in range(0, n-i-1):
                while array[j]>array[j+1]:
                    array[j], array[j+1] = array[j+1], array[j]

我想这样读 [-3.4167,-2.0215,-0.4933,1.6397]

预先感谢

其他:

    example=[]
    with open('ex.txt') as f:
        for l in f:
            l=l.strip()
            example.append(l)

    examplesearch=input('select array to sort')
    if (examplesearch == ex1):
    bubbleSort(example)
    print(example)

1 个答案:

答案 0 :(得分:1)

由于您是从文件中读取的,所以输入的数字是字符串,因此Python使用字符串比较(从得到的结果中可以明显看出)。

您必须先转换为float

example = []
with open('ex.txt') as f:
    for l in f:
        l = float(l.strip())
        example.append(l)

BWT,您无需预先创建列表:

with open('ex.txt') as f:
    # 'if number' will handle potential empty line at the end of the file
    output = [float(number.strip()) for number in f if number]