Bubble Sort

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!

C# Lesson 1

Learn how to declare and use variables in the very first lesson from our series on learning C# for beginners.

C# Lesson 11

Lesson 11 in our series about learning C# teaches you about working with using boolean operators to control logic flow.

C# Lesson 2

Learn how to read input from the user in the second lesson from our series on learning C# for beginners.

C# Lesson 10

Lesson 10 in a our series about learning C# teaches you about working with arrays.

Comments

Log in or sign up to leave a comment.