#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    1
    Rep Power
    0

    Implementing a BubbleSort


    I'm attempting to implement a bubble sort in python with the following code but it is not working properly. My thoughts are that the for loop is not restarting. Can someone point out my error. Thanks

    Code:
    def bubbleSort(a):
            for i in range(len(a)):
                    if ((i < (len(a) - 1)) and (a[i] > a[i+1])):
                            temp = a[i]
                            a[i] = a[i + 1]
                            a[i + 1] = temp
                            i = -1
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    83
    Rep Power
    39
    Your for-loop iterates through the items of the list exactly once. But what you want is for it to repeat iterating until no items were swapped - not just once. So you need to add a while loop around the for loop.

IMN logo majestic logo threadwatch logo seochat tools logo