Tuesday 29 July 2014

Bubble Sort Using C#

Something we are calling it as sinking sort, it is simple way of sorting of repedatly steps of list to make it sort. Pass the value of list to one by one until it not swap. The way the comparison sort is similar way as bubble sort.

Bubble sort example image (from Wiki)



Sorting array by using Bubble  sort in C# code;


Code snippt:
class Program
    {
        static void Main(string[] args)
        {
            string InuputString = "Input Array \n";
             Console.WriteLine(InuputString);

             int[] a = { 3, 2, 5, 9, 4, 1, 8 ,3, 8};
             for (int i = 0; i < a.Length ; i++)
             {
                 Console.Write(a[i] + " ");
             }

             SortArray(a);
        }

        // Doing the bubble sort of array
        public static void SortArray(int[] a)
        {
            int t;
            for (int p = 0; p <= a.Length - 2; p++)
            {
                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 by Bubble sort");

            foreach (int o in a)                        
                Console.Write(o + " ");


            Console.Read();
        }
    }


No comments:

Post a Comment