冒泡排序Python

时间:2018-02-06 13:30:49

标签: python bubble-sort

我试图在Python中进行冒泡排序,而不进行功能,导入功能等。

到目前为止我已经得到了这个,但现在我感到难过:p

array = [1, 42, 321, 44, 121, 61, 812, 71, 10, 11]
number = 1
ArrayIndex = 0
numchange = 0
TotalNumberofLoops = 10
OuterLoop = 0
InnerLoop = 0

while OuterLoop < TotalNumberofLoops:
  InnerLoop = OuterLoop + 1
  while InnerLoop < TotalNumberofLoops:
    if array[OuterLoop] < array[InnerLoop]:
      numchange = array[InnerLoop]
      array[OuterLoop] = array[InnerLoop]
      array[InnerLoop] = numchange

    InnerLoop=InnerLoop + 1
  print array
  OuterLoop = OuterLoop + 1

这给出了以下输出:

[812, 42, 321, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 321, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 44, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 121, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 61, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 10, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 11, 11]
[812, 812, 812, 812, 812, 812, 812, 71, 11, 11]

感谢任何解决方案!

2 个答案:

答案 0 :(得分:0)

试试这个:

array = [1, 42, 321, 44, 121, 61, 812, 71, 10, 11]
number = 1
ArrayIndex = 0
numchange = 0
TotalNumberofLoops = 10
OuterLoop = 0
InnerLoop = 0

while OuterLoop < TotalNumberofLoops:
    InnerLoop = OuterLoop + 1
    while InnerLoop < TotalNumberofLoops:
        if array[OuterLoop] < array[InnerLoop]:
            array[OuterLoop], array[InnerLoop] = array[InnerLoop], array[OuterLoop]

        InnerLoop = InnerLoop + 1
    print(array)
    OuterLoop = OuterLoop + 1

这样,元素的交换更加pythonic,也是正确的。

答案 1 :(得分:0)

怎么样

   def bubble_sort(x):
        # bubble sort with early termination - O(N) for nearly sorted
        swapped = False
        if len(x) > 1:
            for i in range(len(x) - 1):
                    if x[i] > x[i + 1]:
                        swapped = True
                        x[i+1], x[i] = x[i], x[i+1]
            if swapped:
                return bubble_sort(x[0:-1])+[x[-1]]
        return x