Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

Source : http://en.wikipedia.org/wiki/Bubble_sort

Code

 

        public static int[] BubbleSort(int[] input)
        {
            StreamWriter sw = new StreamWriter(@"Sorting.txt", true);

            sw.WriteLine("\n\t\t Bubble Sorting \n");

            sw.WriteLine(System.DateTime.Now + "\t input Array \t Total Element \t" + 
input.Length); sw.WriteLine(string.Join(",", input)); int i, j; i = j = 0; int temp = 0; for (i = 0; i < input.Length; i++) { for (j = i + 1; j < input.Length; j++) { if (input[i] < input[j]) { temp = input[i]; input[i] = input[j]; input[j] = temp; } } } sw.WriteLine(System.DateTime.Now + "\t Sorted Array \n" +
string.Join(",", input)); sw.Close(); return input; }

Test Case

        private static void BubbleSortTest()
        {
            List<int> input = new List<int>();
            Random rnd = new Random(1); int maxnumber = 1200;
            input.Clear(); for (int i = 1; i <= maxnumber; i++)
            {
                input.Add(rnd.Next(1, maxnumber));
            }
            Sorting.BubbleSort(input.ToArray()); input.Clear();
            maxnumber = 100000; for (int i = 1; i <= maxnumber; i++)
            {
                input.Add(rnd.Next(1, maxnumber));
            }
            Sorting.BubbleSort(input.ToArray());
            input.Clear(); maxnumber = 10000;
            for (int i = 1; i <= maxnumber; i++)
            {
                input.Add(rnd.Next(1, maxnumber));
            }
            Sorting.BubbleSort(input.ToArray());
        }