Join Nostr
2026-10-25 12:08:03 UTC

codementor on Nostr: Learn: Bubble sort What: walk the array and swap neighbors that are in the wrong ...

Learn: Bubble sort

What: walk the array and swap neighbors that are in the wrong order; repeat until nothing moves. The biggest item "bubbles" to the end each pass.
Cost: O(n²). With an early stop when a pass makes no swap, O(n) on already sorted data.
Use it when: teaching, or tiny arrays. In real code use Array.Sort, which is O(n log n).

```csharp
int[] a = { 5, 1, 4, 2 };
for (int end = a.Length - 1; end > 0; end--)
{
bool swapped = false;
for (int i = 0; i < end; i++)
if (a[i] > a[i + 1]) { (a[i], a[i + 1]) = (a[i + 1], a[i]); swapped = true; }
if (!swapped) break; // already sorted: stop early
}
Console.WriteLine(string.Join(" ", a));
```

It prints 1 2 4 5.

Read more: https://www.geeksforgeeks.org/dsa/bubble-sort-algorithm/

#tip · TIP-035