122Ml 发表于 2023-9-25 19:14:42

关于Python中的冒泡排序

以下是我写的一段关于冒泡排序的代码:
str=[]
s=input()
x=1
i=0
j=0

while(x<len(s)):
    if(s.isalnum and s!=',' and s!='[' and s!=']'):
      str.append(int(s))
      x+=1
    else:
      x+=1

while(i<len(str)):
    while(j<len(str)-1):
      if(str<str):
            t=str; str=str; str=t;
      j+=1
    i+=1

print(str)   

输入:
期待输出:
实际输出:

请问:
①为什么我写的冒泡排序没有起到应有的效果?
②为什么实际输出数字前有空格?

求大佬解答!!!

isdkz 发表于 2023-9-25 19:14:55

首先,针对第一个问题,你的冒泡排序算法有些问题。在你的代码中,你只进行了一次冒泡排序,而实际上,冒泡排序需要多次遍历才能保证所有元素都被正确排序。你需要在外层再套一层循环,用于控制冒泡排序的次数。修改后的代码如下:

str=[]
s=input()
x=1

while(x<len(s)):
    if(s.isalnum and s!=',' and s!='[' and s!=']'):
      str.append(int(s))
      x+=1
    else:
      x+=1

for i in range(len(str)-1):
    for j in range(len(str)-1-i):
      if str < str:
            str, str = str, str

print(str)


其次,关于实际输出数字前有空格的问题,这是因为你在输出列表时,每个元素之间都有一个空格。可以使用join函数来避免这个问题,修改后的代码如下:

str=[]
s=input()
x=1

while(x<len(s)):
    if(s.isalnum and s!=',' and s!='[' and s!=']'):
      str.append(int(s))
      x+=1
    else:
      x+=1

for i in range(len(str)-1):
    for j in range(len(str)-1-i):
      if str < str:
            str, str = str, str

print("[{}]".format(",".join(str)))


希望能够帮到你!
页: [1]
查看完整版本: 关于Python中的冒泡排序