在课堂上我们正在进行排序算法,虽然我在谈论它们和编写伪代码时理解它们很好,但我在为它们编写实际代码时遇到了问题。
这是我在Python中的尝试:
mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
现在,这(据我所知)正确排序,但一旦完成它就会无限循环。
如何修复此代码以使函数正确完成并正确排序任何(合理)大小的列表?
附:我知道我不应该在一个函数中有真正的打印,我应该有一个返回,但我还没有这样做,因为我的代码还没有真正起作用。
为了解释你的脚本现在无法正常工作的原因,我将把变量unsorted
重命名为sorted
。
首先,您的列表尚未排序。当然,我们将sorted
设置为False
。
一旦我们启动while
循环,我们就会假设列表已经排序。这个想法是这样的:一旦我们找到两个不正确顺序的元素,我们就将sorted
设置回False
。只有在错误的顺序中没有元素时,sorted
才会保留True
。
sorted = False # We haven't started sorting yet
while not sorted:
sorted = True # Assume the list is now sorted
for element in range(0, length):
if badList[element] > badList[element + 1]:
sorted = False # We found two elements in the wrong order
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
# We went through the whole list. At this point, if there were no elements
# in the wrong order, sorted is still True. Otherwise, it's false, and the
# while loop executes again.
还有一些小问题可以帮助代码提高效率或可读性。
for
循环中,您使用变量element
。从技术上讲,element
不是一个元素;它是表示列表索引的数字。而且,它很长。在这些情况下,只需使用临时变量名称,如i
作为“index”。
for i in range(0, length):
range
命令也可以只使用一个参数(名为stop
)。在这种情况下,您将获得从0到该参数的所有整数的列表。
for i in range(length):
def bubble(bad_list):
(badList[i+1], badList[i])
是(3, 5)
),然后被分配到左侧的两个变量((badList[i], badList[i+1])
)。
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
把它们放在一起,你得到这个:
my_list = [12, 5, 13, 8, 9, 65]
def bubble(bad_list):
length = len(bad_list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(length):
if bad_list[i] > bad_list[i+1]:
sorted = False
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
bubble(my_list)
print my_list
(顺便说一句,我也删除了你的打印声明。)
def bubble_sort(l):
exchanged = True
iteration = 0
n = len(l)
while(exchanged):
iteration += 1
exchanged = False
# Move the largest element to the end of the list
for i in range(n-1):
if l[i] > l[i+1]:
exchanged = True
l[i], l[i+1] = l[i+1], l[i]
n -= 1 # Largest element already towards the end
print 'Iterations: %s' %(iteration)
return l
def bubbleSort(alist):
if len(alist) <= 1:
return alist
for i in range(0,len(alist)):
print "i is :%d",i
for j in range(0,i):
print "j is:%d",j
print "alist[i] is :%d, alist[j] is :%d"%(alist[i],alist[j])
if alist[i] > alist[j]:
alist[i],alist[j] = alist[j],alist[i]
return alist
alist = [54,26,93,17,77,31,44,55,20,-23,-34,16,11,11,11]
打印泡泡排序(列表)
def bubble_sort(a):
t = 0
sorted = False # sorted = False because we have not began to sort
while not sorted:
sorted = True # Assume sorted = True first, it will switch only there is any change
for key in range(1,len(a)):
if a[key-1] > a[key]:
sorted = False
t = a[key-1]; a[key-1] = a[key]; a[key] = t;
print a
一个更简单的例子:
a = len(alist)-1
while a > 0:
for b in range(0,a):
#compare with the adjacent element
if alist[b]>=alist[b+1]:
#swap both elements
alist[b], alist[b+1] = alist[b+1], alist[b]
a-=1
这简单地将元素从0转换为a(基本上,该循环中的所有未排序元素)并将其与其相邻元素进行比较,并且如果它大于其相邻元素则进行交换。在循环结束时,最后一个元素被排序,并且该过程在没有它的情况下再次运行,直到所有元素都已排序。
sort
是否真实无需条件。
请注意,此算法仅在交换时考虑数字的位置,因此重复的数字不会影响它。
PS。我知道这个问题发布已经很久了,但我只想分享这个想法。
def bubble_sort(li):
l = len(li)
tmp = None
sorted_l = sorted(li)
while (li != sorted_l):
for ele in range(0,l-1):
if li[ele] > li[ele+1]:
tmp = li[ele+1]
li[ele+1] = li [ele]
li[ele] = tmp
return li
def bubbleSort ( arr ):
swapped = True
length = len ( arr )
j = 0
while swapped:
swapped = False
j += 1
for i in range ( length - j ):
if arr [ i ] > arr [ i + 1 ]:
# swap
tmp = arr [ i ]
arr [ i ] = arr [ i + 1]
arr [ i + 1 ] = tmp
swapped = True
if __name__ == '__main__':
# test list
a = [ 67, 45, 39, -1, -5, -44 ];
print ( a )
bubbleSort ( a )
print ( a )
def bubblesort(array):
for i in range(len(array)-1):
for j in range(len(array)-1-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return(array)
print(bubblesort([3,1,6,2,5,4]))
由愤怒和马丁科特提供的答案解决了无限循环的问题,但我的代码仍然无法正常工作(对于更大的列表,它不会正确排序。)。我最终抛弃了unsorted
变量并改为使用计数器。
def bubble(badList):
length = len(badList) - 1
n = 0
while n < len(badList):
for element in range(0,length):
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
n = 0
else:
n += 1
return badList
if __name__ == '__main__':
mylist = [90, 10, 2, 76, 17, 66, 57, 23, 57, 99]
print bubble(mylist)
如果有人能提供关于如何在评论中改进我的代码的任何指示,那将非常感激。
试试这个
a = int(input("Enter Limit"))
val = []
for z in range(0,a):
b = int(input("Enter Number in List"))
val.append(b)
for y in range(0,len(val)):
for x in range(0,len(val)-1):
if val[x]>val[x+1]:
t = val[x]
val[x] = val[x+1]
val[x+1] = t
print(val)
我想分享我的解决方案:
def bubble_sort(list_):
for i in range(len(list_)):
for j in range(i, len(list_)):
if a[i] > a[j]:
a[i], a[j] = a[j], a[i]
return list_
测试示例:
a = [8,1,2,4,1,3,5,1,5,6,1,8]
bubble_sort(a)
结果:
[1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 8, 8]
冒泡排序的目的是在每一轮中移动较重的物品,同时将较轻的物品向上移动。在内部循环中,您比较元素,您不必在每个回合中迭代整个列表。最重的已经放在最后。交换变量是一个额外的检查,因此我们可以标记列表现在已排序,并避免继续进行不必要的计算。
def bubble(badList):
length = len(badList)
for i in range(0,length):
swapped = False
for element in range(0, length-i-1):
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
swapped = True
if not swapped: break
return badList
你的版本1,更正:
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
unsorted = False
for element in range(0,length):
#unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
unsorted = True
#print badList
#else:
#unsorted = True
return badList
idk如果这可能会帮助你9年后...它是一个简单的冒泡排序程序
l=[1,6,3,7,5,9,8,2,4,10]
for i in range(1,len(l)):
for j in range (i+1,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
def merge_bubble(arr):
k = len(arr)
while k>2:
for i in range(0,k-1):
for j in range(0,k-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
break
else:
if arr[0] > arr[1]:
arr[0],arr[1] = arr[1],arr[0]
return arr
def bubble_sort(l):
for i in range(len(l) -1):
for j in range(len(l)-i-1):
if l[j] > l[j+1]:
l[j],l[j+1] = l[j+1], l[j]
return l
def bubbleSort(a):
def swap(x, y):
temp = a[x]
a[x] = a[y]
a[y] = temp
#outer loop
for j in range(len(a)):
#slicing to the center, inner loop, python style
for i in range(j, len(a) - j):
#find the min index and swap
if a[i] < a[j]:
swap(j, i)
#find the max index and swap
if a[i] > a[len(a) - j - 1]:
swap(len(a) - j - 1, i)
return a
当你使用负面含义的变量名时会发生这种情况,你需要反转它们的值。以下将更容易理解:
sorted = False
while not sorted:
...
另一方面,算法的逻辑略微偏离。您需要检查for循环期间是否交换了两个元素。这是我写它的方式:
def bubble(values):
length = len(values) - 1
sorted = False
while not sorted:
sorted = True
for element in range(0,length):
if values[element] > values[element + 1]:
hold = values[element + 1]
values[element + 1] = values[element]
values[element] = hold
sorted = False
return values
你使用Unsorted变量是错误的;你想要一个变量,告诉你是否交换了两个元素;如果你已经这样做了,你可以退出你的循环,否则你需要再次循环。要修复你在这里得到的东西,只需将“unsorted = false”放在你的if的主体中;删除你的其他情况;并在你的for
循环之前放置“unsorted = true”。
def bubble_sort(l):
for passes_left in range(len(l)-1, 0, -1):
for index in range(passes_left):
if l[index] < l[index + 1]:
l[index], l[index + 1] = l[index + 1], l[index]
return l
#A非常简单的功能,可以通过减少第二个数组的问题空间来优化(显然)。但是相同的O(n ^ 2)复杂度。
def bubble(arr):
l = len(arr)
for a in range(l):
for b in range(l-1):
if (arr[a] < arr[b]):
arr[a], arr[b] = arr[b], arr[a]
return arr
你在那里遇到了一些错误。第一个是长度,第二个是未使用的(如McWafflestix所述)。如果要打印它,您可能还想返回列表:
mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 2
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
unsorted = True
return badList
print bubble(mylist)
eta:你是对的,上面的马车就像地狱一样。我不喜欢通过更多的例子进行测试。
def bubble2(badList):
swapped = True
length = len(badList) - 2
while swapped:
swapped = False
for i in range(0, length):
if badList[i] > badList[i + 1]:
# swap
hold = badList[i + 1]
badList[i + 1] = badList[i]
badList[i] = hold
swapped = True
return badList
我是一个新鲜的初学者,昨天开始阅读Python。在你的例子的启发下,我创造了80多种风格的东西,但它仍然有点有用
lista1 = [12, 5, 13, 8, 9, 65]
i=0
while i < len(lista1)-1:
if lista1[i] > lista1[i+1]:
x = lista1[i]
lista1[i] = lista1[i+1]
lista1[i+1] = x
i=0
continue
else:
i+=1
print(lista1)
原始算法的问题在于,如果列表中的数字更低,则不会将其带到正确的排序位置。程序需要每次都返回到开头,以确保数字一直排序。
我简化了代码,它现在适用于任何数字列表,无论列表如何,即使有重复的数字。这是代码
mylist = [9, 8, 5, 4, 12, 1, 7, 5, 2]
print mylist
def bubble(badList):
length = len(badList) - 1
element = 0
while element < length:
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
element = 0
print badList
else:
element = element + 1
print bubble(mylist)