Implementing Bubble Sort in C#

Sorting is used for arranging numbers stored in array in ascending or descending order and there are different type of algorithms to sort an array. In this section I am using Bubble sort to sort an array.

Here is the program :

using System;

namespace bubble_sort

{

    class Program

    {

        static void Main(string[] args)

        {

            Program p = new Program();

            int[] arr = new int[50]; // declaring array to store elements

            int n;

            Console.WriteLine("Enter no of elements you want to store in an array");

            n = Convert.ToInt32(Console.ReadLine()); // taking input from user

            Console.WriteLine("Enter elements in an array");

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

            {

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

            }

            p.bubblesort(arr, n);

            Console.ReadKey();

        }

        public void bubblesort(int[] arr, int n)

        {

            int temp;

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

            {

                for (int j = 1; j <= n - i; j++)

                {

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

                    {

                        temp = arr[j];

                        arr[j] = arr[j + 1];

                        arr[j + 1] = temp;

                    }

                }

            }

            Console.WriteLine("Array after sorting");

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

            {

                Console.WriteLine(arr[i]);

            }

        }

    }

}

Ebook Download
View all
Learn
View all