Sunday 10 August 2014

Bubble Sort using C#

Bubble Sort:
Bubble sort algorithm works by repeatedly traversing through the list to be sorted, comparing pair of adjacent elements and exchanging them if they are not in order. In each traversal the algorithm puts one element to its correct position in final sorted array. Although the algorithm is simple and easy to implement but is less efficient for large lists.
For implementation the algorithm requires two nested loops. The outer loop iterates through each of the element in the list (size of list is n) while the inner loop iterates n times for the first time, n-1 times for second, n-2 for third time and so on. The purpose of inner loop is to put the next largest element is being put into place. The inner loop therefore does the comparing and swapping of adjacent elements.

Time Complexity: Worst and Average Case: O(n2)

    
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DataStructureAlgoriths
{
    class ArrayBubble
    {
        public void BubbleSort()
        {
            int[] arr = new int[] { 1, 4, 7, 3, 9, 8 };
            int upper = arr.Length - 1;
            int temp = 0;
            for (int outer = upper; outer >=1 ; outer--)
            {
                for (int inner = 0; inner <= outer-1; inner++)
                {
                    if (arr[inner] > arr[inner + 1])
                    {
                        temp = arr[inner];
                        arr[inner] = arr[inner + 1];
                        arr[inner + 1] = temp;

                    }
                }
            }
            foreach (var item in arr)
            {
                Console.WriteLine(item);   
            }
        }

    }
}

    class Program
    {
        static void Main(string[] args)
        {
            ArrayBubble L = new ArrayBubble();
            L.BubbleSort();
            Console.ReadLine();
        }
    }


No comments:

Post a Comment