Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 35 / 68

Understanding how bubble sort works

This lesson covers implementing bubble sort in R, 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 through the temporary variable tmp when they are out of order.

A common early stumble is the swap itself. You have to park one value in a temporary variable first, or the original is lost.

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 R 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)