1. Home
  2. Docs
  3. C# Programming
  4. Algorithms
  5. Bubble Sort

Bubble Sort

static void bubbleSort<T>(ref T[] x)
{
   bool exchanges;
   do
   {
      exchanges = false;
      for (int i = 0; i < x.Length - 1; i++)
      {
         if (x[i] > x[i + 1])
         {
         // Exchange elements
         T = x[i];
         x[i] = x[i + 1];
         x[i + 1] = temp;
         exchanges = true;
         }
      }
   } while (exchanges);
}

Improved Code

static void bubbleSortV2<T>(ref T[] x)
{
   for (int pass = 1; pass < x.Length - 1; pass++)
   {
      // Count how many times this next looop
      // becomes shorter and shorter
      for (int i = 0; i < x.Length - pass; i++)
      {
         if (x[i] > x[i + 1])
         {
            // Exchange elements
            T temp = x[i];
            x[i] = x[i + 1];
            x[i + 1] = temp;
         }
      }
   }
}

Type 3

static void bubbleSortV3<T>(ref T[] x)
{
   bool exchanges;
   int n = x.Length;
   do
   {
      n--; // Make loop smaller each time.
      // and assume this is last pass over array
      exchanges = false;
      for (int i = 0; i < x.Length-1; i++)
      {
         if (x[i] > x[i + 1])
         {
            // Exchange elements
            T temp = x[i];
            x[i] = x[i + 1];
            x[i + 1] = temp;
            exchanges = true;
         }
      }
   } while (exchanges);
}

Bubble Sort Range

static void bubbleSortRange(ref int[] x)
{
    int lowerBound = 0; // First position to compare.
    int upperBound = x.Length-1; // First position NOT to compare.
    int n = x.Length-1;
    // Continue making passes while there is a potential exchange.
    while (lowerBound <= upperBound)
    {
    // assume impossibly high index for low end.
        int firstExchange = n;
        // assume impossibly low index for high end.
        int lastExchange = -1;
        // Make a pass over the appropriate range.
        for (int i=lowerBound; i<upperBound; i++)
        {
            if (x[i] > x[i+1])
            {
                // Exchange elements
                int temp = x[i];
                x[i] = x[i+1];
                x[i+1] = temp;
                // Remember first and last exchange indexes.
                if (i<firstExchange)
                { // True only for first exchange.
                    firstExchange = i;
                }
                lastExchange = i;
            }
        }
        //--- Prepare limits for next pass.
        lowerBound = firstExchange-1;
        if (lowerBound < 0)
        {
            lowerBound = 0;
        }
        upperBound = lastExchange;
    }
}
Was this article helpful to you? Yes No

How can we help?