Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 35 / 68

Understanding how bubble sort works

This lesson covers implementing bubble sort in Objective-C, 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 makes a mutable array with [@[...] mutableCopy], compares neighbouring elements with integerValue in a double for loop, and swaps them with exchangeObjectAtIndex:withObjectAtIndex: when they are out of order.

A common early stumble is choosing between NSArray and NSMutableArray. Swapping elements requires a mutable array, so you convert with mutableCopy first.

In practice you would use an optimised approach such as sortedArrayUsingSelector:, 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 Objective-C 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)