Visualising Bubble Sort in Python

sammyGH
by sammyGH · 2 posts
3 years ago in Python
Posted 3 years ago · Author
Hey guys im back with some more Python, I think someone was telling me to post more in this section so here I am.

There are many ways to visualise things using Python, but how would one visualise Bubble Sort?

Incase you're new to programming and dont know exactly what Bubble Sort is here is the definition :
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
For more information I would suggest watching YouTube videos on it and looking at this geeks for geeks page: https://www.geeksforgeeks.org/bubble-sort/
When it comes to programming geeksforgeeks is a good tool to learn and see examples in multiple different language.


So I have a main program where i can pick and choose how my data is generated/drawn (I have a draw data function.) then i have another file called Bubble Sort where i have my code.

Code
import time


def bubble_sort(data, draw_data, wait_time):
    length_of_array = len(data)
    # Goes through all the elements in the array
    for i in range(length_of_array):
        for j in range(0, length_of_array - i - 1):
            # Swaps if the next element is smaller.
            if data[j] > data[j + 1]:
                data[j], data[j + 1] = data[j + 1], data[j]
                draw_data(data, ['crimson' if x == j or x == j + 1 else 'deep sky blue' for x in range(len(data))])
                time.sleep(wait_time)
    draw_data(data, ['lime' for i in range(len(data))])
    return data


Let me know what you guys think and if you think there is a better way to do this. Thank you.
Posted 3 years ago
Show us the draw_data function you used too, maybe we could help out with that?

Create an account or sign in to comment

You need to be a member in order to leave a comment

Sign in

Already have an account? Sign in here

SIGN IN NOW

Create an account

Sign up for a new account in our community. It's easy!

REGISTER A NEW ACCOUNT