Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 35 / 68

Understanding How Bubble Sort Works

In this lesson you will implement bubble sort and understand the basic mechanics of sorting. This is for anyone searching for "Ruby sort implementation".

Bubble sort is a simple algorithm that repeatedly compares two neighbouring values and swaps them when they are the wrong way round. The name comes from the way larger bubbles gradually rise to the surface.

The sample code uses nested each blocks: the outer one sweeps the whole array repeatedly while the inner one compares and swaps neighbouring elements. Writing arr[j], arr[j + 1] = arr[j + 1], arr[j] swaps two values without a temporary variable - another idiomatic Ruby touch.

A common stumbling block for beginners is narrowing the inner loop's range correctly. Comparing all the way to the end every time wastes work on the part that is already sorted, so the range needs to shrink pass by pass.

You will almost never write it yourself in production code, but it is the standard first step in learning algorithms. It is not efficient in terms of computational complexity, and in practice you would use the optimised sort method.

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

๐Ÿงช This site can't compile or run Ruby 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)