Bubble Sorting Algorithm in C#

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that needs to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because the smaller elements bubble towards the top of the list.

Bubble sort is also referred to as the sinking sort or comparison sort.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace BubbleSort

{

    class BubbleSort

    {

        static int BubbleSorting()

        {

            Console.Write("\nProgram for sorting using Bubble Sort Algorithm");

            Console.Write("\n\nEnter the total number of elements: ");

            int max = Convert.ToInt32(Console.ReadLine());

 

            int[] numarr = new int[max];

 

            for (int i = 0; i < max; i++)

            {

                Console.Write("\nEnter [" + (i + 1).ToString() + "] element: ");

                numarr[i] = Convert.ToInt32(Console.ReadLine());

            }

 

            Console.Write("Input int array   : ");

            for (int k = 0; k < max; k++)

                Console.Write(numarr[k] + " ");

            Console.Write("\n");

 

            for (int i = 1; i < max; i++)

            {

                for (int j = 0; j < max - i; j++)

                {

                    if (numarr[j] > numarr[j + 1])

                    {

                        int temp = numarr[j];

                        numarr[j] = numarr[j + 1];

                        numarr[j + 1] = temp;

                    }

                }

                Console.Write("Iteration " + i.ToString() + ": ");

                for (int k = 0; k < max; k++)

                    Console.Write(numarr[k] + " ");

                Console.Write("\n");

 

            }

 

            Console.Write("\n\nThe numbers in ascending orders are given below:\n\n");

            for (int i = 0; i < max; i++)

            {

                Console.Write("Sorted [" + (i + 1).ToString() + "] element: ");

                Console.Write(numarr[i]);

                Console.Write("\n");

            }

            return 0;

        }

 

        static void Main(string[] args)

        {

            BubbleSorting();

            Console.ReadLine();

        }

    }

}

 

Ebook Download
View all
Learn
View all