AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Tuesday, 18 December 2018

Bubble sort in c#

Bubble sort is the simplest sorting algorithm. As per name the sorting will be done sequentially by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted.

Input 98 56 49 38 15
Pass 1 56 98 49 38 15
Pass 2 56 49 98 38 15
Pass 3 56 49 38 98 15
Pass 4 56 49 38 15 98
Pass 5 49 56 38 15 98
Pass 6 49 38 56 15 98
Pass 7 49 38 15 56 98
Pass 8 49 38 15 56 98
Pass 9 38 49 15 56 98
Pass 10 38 15 49 56 98
Pass 11 38 15 49 56 98
Pass 12 38 15 49 56 98
Pass 13 15 38 49 56 98
Pass 14 15 38 49 56 98
Pass 15 15 38 49 56 98
Pass 16 15 38 49 56 98
C# program for bubble sort

/*
 * C# Program for Bubble Sort
 */
using System;
class BubbleSort
{
        static void Main(string[] args)
        {
            int[] a = { 98, 56, 49, 38, 15 };  
            int t;
            Console.WriteLine("Array is : ");
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine(a[i]);
            }
            for (int j = 0; j <= a.Length - 2; j++)
            {
                for (int i = 0; i <= a.Length - 2; i++)
                {
                    if (a[i] > a[i + 1])
                    {
                        t = a[i + 1];
                        a[i + 1] = a[i];
                        a[i] = t;
                    }
                }
            }
            Console.WriteLine("Sorted Array :");
            foreach (int aray in a)                         
                Console.Write(aray + " ");
            Console.ReadLine();
        }
    }

Output of Program:
Array is :
98
56
49
38
15

Sorted Array :
15
38
49
56
98

Complexity
The above function always runs O(n^2) time even if the array is sorted.

0 comments :

Post a comment

  • Popular Posts
  • Comments