Hi Frnds ...

i want to know , how to optimize bubble sort ,
if you realize that at the end of the i-th pass, the last i numbers are already in place. Consider the sequence {3, 9, 1, 7}. After the first pass, the 9 will end up in the final position; we need not consider it on subsequent passes , so for to reduce this
comparison again and again , what i hav to do ???

using System;

class AscendingBubbleSort
{

   public static void Main()
   {
      int i = 0, j = 0, t = 0;
      int []c = new int[20];
      for ( i = 0; i < 20; i++ )
      {
         Console.WriteLine ( "Enter Value p[{0}]:", i );
         c[i] = int.Parse ( Console.ReadLine() );
      }
// Sorting: Bubble Sort
      for ( i = 0; i < 20; i++ )
      {
         for ( j = i + 1; j < 20; j++ )
         {
            if ( c[i] > c[j] )
            {
               Console.WriteLine ( "c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j] );
               t = c[i];
               c[i] = c[j];
               c[j] = t;
            }
         }
      }
      Console.WriteLine ( "Here comes the sorted array:" );     // Print the contents of the sorted array
      for ( i = 0; i < 20; i++ )
      {
         Console.WriteLine ( "c[{0}]={1}", i, c[i] );
      }
   }

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

> i want to know , how to optimize bubble sort
Switch to a faster algorithm. :D Bubble sort is one of the least efficient sorting algorithms, to the point that trying to optimize it is wasted effort when even switching to another quadratic performance algorithm like insertion sort would give you better results.

But one way to optimize bubble sort is stopping the algorithm if no swaps were made during an iteration.

for ( i = 0; i < 20; i++ )
{
    bool done = true;

    for ( j = i + 1; j < 20; j++ )
    {
        if ( c[i] > c[j] )
        {
            t = c[i];
            c[i] = c[j];
            c[j] = t;
            done = false;
        }
    }

    if ( done )
        break;
}

If no swaps are made in the inner loop, the array is sorted and no more work needs to be done.

This question has already been answered. Start a new discussion instead.