【发布时间】:2019-05-07 17:26:33
【问题描述】:
似乎找不到任何关于此的内容,因为我无法正确地用词。基本上,当我将列表从负数排序到最低负数然后读取正数时,假设它是 [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)
【问题讨论】:
-
附带说明,您为什么使用
while而不是if? -
当我用
[1.6397, -2.0215, -0.4933, -3.4167]调用这个函数时,我得到了你期望的输出 -[-3.4167, -2.0215, -0.4933, 1.6397]。 -
哎呀,是的,这是我的代码上的“如果”,我只是冲了那个例子,我的错
-
当我运行这段代码时,它会正确地对数组进行排序。向我们展示调用此函数并打印结果的代码。
-
我的数字是从 txt 文件中导入的您是在将数字转换为实际的浮点值,还是仍然是字符串?
标签: python python-3.x sorting bubble-sort