Medium csharp

Bubble sort

Problem

Sort {5,1,4,2,8} using bubble sort and print.

Hints
  • Compare adjacent pairs and swap.

Your practice code

Ready — edit the code above and click Run.

Solution

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.

Explanation

Bubble sort is O(n²)—know it for interviews even if you use Array.Sort in production.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details