简体   繁体   中英

Bubble Sort Python

I'm trying to do Bubble Sort in Python, without making functions, importing functions, etc.

I've gotten this so far, but now I'm stumped :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

This gives the following output:

[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]

Thanks for any solutions!

Try this:

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

This way the swap of elements is more pythonic and also correct.

How about

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM