Computer Science, asked by priyakhosla6723, 1 year ago

How can we calculate the total number of comparisons in bubble sort with n elements after k iterations?

Answers

Answered by franktheruler
0

Answer:

Through a program we calculate the total number of comparisons in bubble sort with n elements after k iterations

Let, total number of elements are 5 means n = 5.

Program :

 #include <stdio.h>

#define SIZE 5

int main ()

{

  int data[ SIZE ] = { 14, 33, 27, 35, 10 };

  int p, i, temp ;

  //printing data items

 for ( i = 0; i < SIZE; ++i )

  {

     printf ("%d", data [ i ]);

  }

 //bubble sort

  for (pass = 1; pass < SIZE; ++ p ) // loop

  {

     for (i = 0; i < SIZE - 1; ++ i )

     {

        //comparing successive elements and swapping

        if (data [ i ]  >  data [ i + 1 ] )

        {

           temp = data [ i ];

           data [ i ] = data [ i + 1 ];

           data [ i + 1 ] = temp;

        }

     }

  }

  printf ("\n Data items in ascending order:\n " );

  for (i= 0; i < SIZE; ++i)

  {

     printf (" % d", data[ i ]);

  }

  return 0;

}

Main logic of bubble sort is highlighted below :

  if (data [ i ]  >  data [ i + 1 ] )

        {

           temp = data [ i ];

           data [ i ] = data [ i + 1 ];

           data [ i + 1 ] = temp;

        }

Similar questions