Bubble Sort

blog post header image

Sample source code for implementing bubble sort in C# with an accompanying video explaining how to do it yourself.

Bubble sort is good introduction to writing sorting algorithms. The idea is simple. Iterate over a collection over and over again swapping pairs of items until the entire collection is in the correct order. Watch the video below or take a look at our source code to make a bubble sort implementation on your own. We're planning to make an entire series explaining and implementing common sorts in C#, so come back for more!


using System;
using System.Collections.Generic;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            var unsortedList = GetUnsortedList(20);
            Console.WriteLine(string.Join(", ", unsortedList));

            bool swapped;
            int n = unsortedList.Length - 1;
            do
            {
                swapped = false;

                for (var i = 0; i < n; i++)
                {
                    var element1 = unsortedList[i];
                    var element2 = unsortedList[i + 1];

                    if (element1 > element2)
                    {
                        unsortedList[i] = element2;
                        unsortedList[i + 1] = element1;
                        swapped = true;
                    }
                }

                n--;

                Console.WriteLine(string.Join(", ", unsortedList));
            } while (swapped);


            Console.WriteLine(string.Join(", ", unsortedList));
        }

        private static int[] GetUnsortedList(int length)
        {
            var unsortedList = new List(); 

            Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                unsortedList.Add(random.Next(100));
            }

            return unsortedList.ToArray();
        }
    }
}

Recommended posts

We have similar articles. Keep reading!