0

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!

3
  • 4
    Your swapping logic is wrong. Correct it. OR you can use a, b = b, a for swapping in python. Commented Feb 6, 2018 at 13:33
  • @KeyurPotdar Python seems like cheating sometimes! Commented Feb 6, 2018 at 13:39
  • It looks like you misspelled "OuterLoop" as "InnerLoop" in the first line of the swap sequence - a mistake that's much easier to spot if somebody else made it. Commented Feb 6, 2018 at 14:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This really helped. I forgot about my swapping logic :p
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.