DEV Community

ann lin
ann lin

Posted on

5 1

Bubble Sort in Python

Become a Software Engineer -> Pass Technical Interview -> Be darn good at Data Structure and Algorithms -> Starting with Sorting Algorithms -> 1. Bubble Sort

Bubble Sort (Decreasing Order)

def bubblesort(array):
    # we minus 1 because we are always comparing the current value with the next value
    lengthOfArray = len(array) - 1
    # numbe of rounds will be the total length - 1, for array with length 5, we will do 4 rounds: 0 and 1, 1 and 2, 2 and 3, 3 and 4.
    for i in range(lengthOfArray):
        # at each round, we compare the current j with the next value
        for j in range(lengthOfArray - i):
            # only swap their positions if left value < right value as we aim to move all the small values to the back
            if array[j] < array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]

    return array


array = [2, 1, 5, 4, 3]
print bubblesort(array)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (6)

Collapse
 
chenge profile image
chenge

The video is funny, good idea. Numbers are really boring.

Collapse
 
annlin profile image
ann lin

aww thanks, took the chance to showcase my favourite people too :)

Collapse
 
chenge profile image
chenge

I want to see quick sort. When will you publish it?

Thread Thread
 
annlin profile image
ann lin • Edited

Your wish is my command. Coming up soon :)

Thread Thread
 
chenge profile image
chenge

Thanks for caring, expecting..., :)

Collapse
 
sekr4 profile image
Sebastian

thx :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay