Sunday 24 July 2016

Bubble sort Algorithm in c#?



In Bubble sort algorithm, we take first element from array and compare with next element in array. If first number id greater than next number then we interchange their place. If first no less than next element then no change. Again if second no is greater than third element then interchanging their places? Like this we iterating loop until we sort the no.

Example:-

            Console.Write("\n ------Bubble Sort Algorithm ------");
            Console.Write("\nProgram for sorting numbers using Bubble Sort Algorithm");
            Console.Write("\n\nEnter the total number of elements: ");
            int countItem = Convert.ToInt32(Console.ReadLine());

            int[] numArr = new int[countItem];

            for (int i = 0; i < countItem; i++)
            {
                Console.Write("\nEnter [" + (i + 1).ToString() + "] element: ");
                numArr[i] = Convert.ToInt32(Console.ReadLine());
            }

            Console.Write("Input Elements in Array :");
            for (int k = 0; k < countItem; k++)
            {
                Console.Write(numArr[k] + " ");
            }

            Console.Write("\n");


            for (int i = 1; i < countItem; i++) // iterate loop by no of Elements
            {
                for (int j = 0; j < countItem - i; j++) //
                {
                    if (numArr[j] > numArr[j + 1]) // if no grated than adjecent no
                    {
                        int temp = numArr[j];  // assign value in temp
                        numArr[j] = numArr[j + 1]; // assign adjecent
                        numArr[j + 1] = temp;
                    }
                }
                Console.Write("No of Iteration :" + i.ToString() + ": ");// show how many times array  shuffled
                for (int k = 0; k < countItem; k++)
                {
                    Console.Write(numArr[k] + " "); // show shuffled array
                }
                Console.Write("\n");
            }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.