Bubble Sort Example in C#

Hi programmers, welcome to new article of c#.net. This post i’ll write programs for bubble sort in c# console application.Bubble sort is a simple sorting algorithm.
it compares each pair of adjacent elements in the array and the elements are exchange if they are not in order. let’s see the codes.

Example
input / output

Directly Test below Codes into Editor.

using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
            int[] arr = new int[55];
            int i, j, n, temp;

            Console.WriteLine("Enter the Size of Array :");
            n = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter the Array Elements :");
            for(i = 0;i < n; i++)
            {
                arr[i] = int.Parse((Console.ReadLine()));
            }
            for(i = 0; i< (n-1);i++)
            {
                for(j = 0;j < n-i-1;j++)
                {
                    if(arr[j] > arr [j+1])
                    {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            Console.WriteLine("After Bubble Sort :");
            for (i = 0; i < n; i++)
                Console.WriteLine(arr[i] + " ");
        }       
    }
}

Happy Coding…Thanks.

Post Author: adama