Learn Computer Science programming - C# and C++ Algorithms

 
Bubble Sort

The bubble sort is the oldest and most simple sort algorithm. It is also the slowest. The bubble compares each item in the list with the item next to it, and swapping them if needed. The algorithm repeats this process until it completes the entire list without swapping any items. Larger values bubble to the bottom and smaller values sink towards the beginning of the list. The bubble sort is considered to be the most inefficient sorting algorithm approaching O(n2).
Code
c_bubblesort.zip
File Size: 22 kb
File Type: zip
Download File

using System;
using System.Collections;

namespace Sort
{
    public class SortBubble
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            int[] numbers = new int[] { 3, 4, 65, 7, 8, 11, 2234, 4, 117 };
            int i, j, tmp, n;

            n = numbers.Length;

            Console.WriteLine("Before");
            Display(numbers);

            for (i = 0; i < n - 1; i++)
            {
                for (j = 0; j < n - 1 - i; j++)
                    if (numbers[j + 1] < numbers[j])
                    {  /* compare the two neighbors */
                        tmp = numbers[j];/* swap numbers[j] and numbers[j+1]      */
                        numbers[j] = numbers[j + 1];
                        numbers[j + 1] = tmp;
                    }
            }
            Console.WriteLine("\r\nAfter");
            Display(numbers);
        }


        static void Display(int[] numbers)
        {
            //Display Array Content
            IEnumerator sorted = numbers.GetEnumerator();
            while (sorted.MoveNext())
            {
                Console.WriteLine(sorted.Current);
            }
        }
    }
}