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 7

You're familiar with "while" loops in C#, but but it's time to learn about "for" loops. Let's get loopy in the 7th lesson in our series about learning C#.

C# Project 2

Test out your knowledge on basic C# programming with a challenging project making a hangman game. Covers lessons 7-12 from the beginner series.

C# Project 1

Test out your knowledge on basic C# programming with a challenging project doing conversions. Covers lessons 1-6 from the beginner series.

C# Lesson 2

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

Comments

Log in or sign up to leave a comment.