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 12

Lesson 12 in a our series about learning C# teaches you about working with methods.

C# Lesson 3

Learn how to do some basic math with C# in the 3rd lesson from our series for beginners learning C#.

C# Lesson 6

Learn about "while" loops, a way to make sections of code repeat, in our 6th lesson in the C# series for beginners.

C# Lesson 8

Characters, the data type that's just a little less useful than a string.

Comments

Log in or sign up to leave a comment.