Bubble Sort

Bubble sort is the first sorting algorithm that you learn in many algorithm classes.

It's not a particularly fast technique, so it's never really used in practice. And generally if you're writing your own sorting algorithm instead of relying on one that your platform provides then you've made some poor decisions.

However bubble sort is simple enough that anyone can understand it, and most programmers can implement it or verify it.

Preparing for visualization

Before we get to the algorithm itself we need to create some useful functions for visualizing what it does.

We're going to be sorting a list of randomly selected numbers. So we'll need a way to visualize an array of numbers.

For this we'll make a simple bar graph. We'll need functions for drawing lines, for erasing lines, and (building on top of that) for drawing arrays of lines.

Initializing a random list

Now we need a function for generating a list of random numbers.

And finally we're onto the bubble sort algorithm itself.

Structurally it's a loop, with an inner loop (i.e a nested loop). In the inner loop it compares two adjacent items from the list. If the first one is bigger than the second one, it's swaps them.

External Links

See Also


Logo + Turtle graphics via Papert.