Python 泡泡作业

Python 泡泡作业,python,algorithm,sorting,bubble-sort,Python,Algorithm,Sorting,Bubble Sort,在课堂上,我们正在做排序算法,虽然我在谈论它们和编写伪代码时对它们理解得很好,但我在为它们编写实际代码时遇到了问题 这是我在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):

在课堂上,我们正在做排序算法,虽然我在谈论它们和编写伪代码时对它们理解得很好,但我在为它们编写实际代码时遇到了问题

这是我在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)
现在,这个(据我所知)排序正确,但一旦完成,它就会无限循环

如何修复此代码以使函数正确完成对任何(合理)大小的列表的排序


另外,我知道我不应该在函数中有打印,我应该有一个返回,但我只是还没有这样做,因为我的代码还没有真正工作。

这就是当你使用负意义的变量名时会发生的情况,你需要反转它们的值。以下内容更容易理解:

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=false”放在if案例主体中;移除你的else案例;然后将“unsorted=true”放在
for
循环的
前面。

这里有几个错误。第一个是长度,第二个是使用unsorted(如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)
埃塔:你说得对,上面的错误太多了。我的缺点是没有通过更多的例子进行测试

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

fury和Martin Cote提供的答案解决了无限循环的问题,但我的代码仍然无法正常工作(对于较大的列表,它无法正确排序)。我最终放弃了未排序的
变量,而是使用了计数器

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)
def气泡(坏列表):
长度=长度(坏名单)-1
n=0
当nbadList[element+1]:
保持=坏列表[元素+1]
坏名单[元素+1]=坏名单[元素]
坏名单[元素]=保留
n=0
其他:
n+=1
返回坏名单
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
mylist=[90,10,2,76,17,66,57,23,57,99]
打印气泡(mylist)
如果有人能在评论中就如何改进我的代码提供任何建议,我们将不胜感激。

def bubble\u sort(l):
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
对于在范围(len(l)-1,0,-1)内的左传递: 对于范围内的索引(向左传递): 如果l[index]
气泡排序的目标是在每一轮中移动底部较重的项目,同时向上移动较轻的项目。在内部循环中,比较元素,您不必在每一轮中迭代整个列表。最重的项目已经排在最后。交换的变量是一个额外的检查,以便我们可以标记列表现在已排序,避免继续进行不必要的计算

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

为了解释脚本现在无法工作的原因,我将变量
unsorted
重命名为
sorted

首先,您的列表尚未排序。当然,我们将
排序
设置为
False

一旦我们启动
while
循环,我们就假设列表已经排序。其思想是:一旦我们发现两个元素的顺序不正确,我们就将
排序的
设置回
False
排序的
只有在没有元素的顺序错误的情况下才会保持
True

还有一些小问题可以帮助代码更加高效或可读

  • for
    循环中,使用变量
    element
    。从技术上讲,
    element
    不是一个元素;它是一个表示列表索引的数字。而且,它相当长。在这种情况下,只需使用一个临时变量名,如
    i
    表示“索引”

  • range
    命令也可以只接受一个参数(名为
    stop
    )。在这种情况下,您将获得从0到该参数的所有整数的列表

    for i in range(length):
    
  • 建议用小写字母加下划线来命名变量。对于像这样的小脚本来说,这是一个非常小的挑剔;它更能让您习惯Python代码最常见的相似之处

    def bubble(bad_list):
    
  • 要交换两个变量的值,请将它们作为元组赋值写入。右侧将作为元组进行求值(例如,
    (badList[i+1],badList[i])
    (3,5)
    ),然后将其赋值给左侧的两个变量(
    (badList[i],badList[i+1])

把它们放在一起,你会得到:

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
(顺便说一句,我也删除了你的打印语句。)

#一个非常简单的函数,可以通过减少第二个数组的问题空间来优化(显然),但同样的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 
def气泡(arr):
l=长度(arr)
对于范围(l)内的a:
对于范围(l-1)内的b:
如果(arr[a]
我是一个新手,昨天开始阅读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)
lista1=[12,5,13,8,9,65]
i=0
而i列表A1[i+1]:
x=列表A1[i]
lista1[i]=lista1[i+1]
列表1[i+1]=x
i=0
持续
其他:
i+=1
打印(列表A1)

原始算法的问题是,如果列表中的数字较低,则无法将其带到正确的排序位置。程序需要
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(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 
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)
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
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
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]))
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)
    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
arr = [5,4,3,1,6,8,10,9] # array not sorted

for i in range(len(arr)):
    for j in range(i, len(arr)):
        if(arr[i] > arr[j]):
            arr[i], arr[j] = arr[j], arr[i]

            print (arr)
def countInversions(arr):
    count = 0
    n = len(arr)
    for i in range(n):
        _count = count
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                count += 1
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
        if _count == count:
            break
    return count
def bubble_sort(lst: list) -> None:
    [swap_items(lst, i, i+1) for left in range(len(lst)-1, 0, -1) for i in range(left) if lst[i] > lst[i+1]]


def swap_items(lst: list, pos1: int, pos2: int) -> None:
    lst[pos1], lst[pos2] = lst[pos2], lst[pos1]
class BubbleSort: 
  def __init__(self, arr):
    self.arr = arr;

  def bubbleSort(self):
    count = 0;
    lastIndex = len(self.arr) - 1;
    
    while(count < lastIndex):
      if(self.arr[count] > self.arr[count + 1]):
        self.swap(count)  
      count = count + 1;

      if(count == lastIndex):
        count = 0;
        lastIndex = lastIndex - 1;   

  def swap(self, count):
    temp = self.arr[count];
    self.arr[count] = self.arr[count + 1];
    self.arr[count + 1] = temp;
    
arr = [9, 1, 5, 3, 8, 2]
p1 = BubbleSort(arr)

print(p1.bubbleSort())
def bubble_sorted(arr:list):
    while True:
        for i in range(0,len(arr)-1):
            count = 0
            if arr[i] > arr[i+1]:
                count += 1
                arr[i], arr[i+1] = arr[i+1], arr[i]
        if count == 0:
            break
    return arr
arr = [30,20,80,40,50,10,60,70,90]
print(bubble_sorted(arr))
#[20, 30, 40, 50, 10, 60, 70, 80, 90]