Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 35 / 68

Understanding how bubble sort works

This lesson covers implementing bubble sort in Julia, with the aim of understanding sorting from the ground up.

Bubble sort repeatedly compares two neighbouring values and swaps them if they are the wrong way round. The name comes from the resemblance to large bubbles gradually rising to the surface.

The sample code uses a double for loop; the inner loop compares the neighbouring elements arr[j] and arr[j+1] and swaps them with the tuple assignment arr[j], arr[j+1] = arr[j+1], arr[j]. Note how concisely Julia expresses a swap.

A common early stumble is that it is not efficient in terms of complexity. You will rarely write one in practice, but it is the classic first step in learning algorithms and appears in most textbooks.

In practice you would use an optimised function such as sort(), but this is an important algorithm for understanding what happens inside one.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Julia directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)