Sort {5,1,4,2,8} using bubble sort and print.
Ready — edit the code above and click Run.
using System;
class Program
{
static void Main()
{
int[] arr = { 5, 1, 4, 2, 8 };
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - 1 - i; j++)
if (arr[j] > arr[j + 1])
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
Console.WriteLine(string.Join(", ", arr));
}
}
Try solving on your own first, then reveal the official answer.
Bubble sort is O(n²)—know it for interviews even if you use Array.Sort in production.