Implement Bubble Sort - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Sort

Description

Implement Bubble Sort

Demo Code

using System;/*from   w  ww.  ja va  2 s . co m*/
class BubbleSorter
{
   // Sort the elements of an array in ascending order
   public static void BubbleSortAscending(int [] bubbles)
   {
      bool swapped = true;
      for (int i = 0; swapped; i++)
      {
         swapped = false;
         for (int j = 0; j < (bubbles.Length - (i + 1)); j++)
         {
            if (bubbles[j] > bubbles[j + 1])
            {
               Swap(j, j + 1, bubbles);
               swapped = true;
            }
         }
      }
   }
   //Swap two elements of an array
   public static void Swap(int first, int second, int [] arr)
   {
      int temp;
      temp = arr[first];
      arr[first] = arr[second];
      arr[second] = temp;
   }
   //Print the entire array
   public static void PrintArray (int [] arr)
   {
      for (int i = 0; i < arr.Length; i++)
      {
         Console.Write("{0}, ", arr[i]);
      }
   }
   public static void Main()
   {
      int [] testScores = {3,5,6,7,54,3,300, 90, 50, 120, 100, 10, 290, 85, 90, 120};
      BubbleSortAscending(testScores);
      Console.WriteLine("The test scores sorted in ascending order:\n");
      for (int i = 0; i < testScores.Length; i++)
      {
         Console.Write("{0}  ", testScores[i]);
      }
   }
}

Result


Related Tutorials