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
Published at
2026-10-25 12:08:03 UTCEvent JSON
{
"id": "72893dca89011ddb8ce89daf132576830690933870174724470a42115c956cd9",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792930083,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Bubble sort\n\nWhat: 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.\nCost: O(n²). With an early stop when a pass makes no swap, O(n) on already sorted data.\nUse it when: teaching, or tiny arrays. In real code use Array.Sort, which is O(n log n).\n\n```csharp\nint[] a = { 5, 1, 4, 2 };\nfor (int end = a.Length - 1; end \u003e 0; end--)\n{\n bool swapped = false;\n for (int i = 0; i \u003c end; i++)\n if (a[i] \u003e a[i + 1]) { (a[i], a[i + 1]) = (a[i + 1], a[i]); swapped = true; }\n if (!swapped) break; // already sorted: stop early\n}\nConsole.WriteLine(string.Join(\" \", a));\n```\n\nIt prints 1 2 4 5.\n\nRead more: https://www.geeksforgeeks.org/dsa/bubble-sort-algorithm/\n\n#tip · TIP-035",
"sig": "2f56e523d51db6f6cda0970c33166b528ec09f00dcede91d412427e77c28412459be9186fd74fa3decc3867a4c3180ca94b8407d1a277fabddc33ccc812040f1"
}