Bubblesort

http://install4install.com

Bubblesort is a sorting technique which arrange elements in the increasing order by moving across the array and swapping the adjacent elements that are out of order.The complexity of bubble sort is O(n2).

The steps followed are :

Program

#include <stdio.h>

void bubble(int [], int);

int main()
{
  int arr[50], n, a, b;
  //printf("Enter number of elements\n");
  scanf("%d", &n);
  //printf("Enter elements of array \n");
  printf("Unsorted list is :\t");
  for (a = 0; a < n; a++)
  {
  scanf("%d", &arr[a]);
  printf("%d\t",arr[a]);
  }
  bubble(arr, n);
  printf("\nSorted list is:\t");
  for ( a = 0 ; a < n ; a++ )
  {
     printf("%d\t", arr[a]);
  }
  return 0;
}

void bubble(int array[], int n)
{
  int a, b, temp;
  for (a = 0 ; a < ( n - 1 ); a++)
  {
    for (b = 0 ; b < n - a - 1; b++)
    {
      if (array[b] > array[b+1])
      {
      	temp         = array[b];
        array[b]   = array[b+1];
        array[b+1] = temp;
      }
    }
  }
}

Run Example Consider an  array with elements 3,7,2,10,1,35,15,5,30,4,8.In order to sort elements,iterations are used.In the first iteration when i=1 sorting is done as given in  Fig 1 and Fig 2.Refer to Fig 3 and 4 for second iteration i.e i=2,Fig 5 and 6 for i=3.Fig 7 and 8 for i=4,Fig 9 and 10 for i=5.Fig 11 and 12 for i =6 respectively.

Screen Shot 2014-06-18 at 3.21.24 PM

Fig 1 : i=1

Screen Shot 2014-06-18 at 3.23.04 PM

Fig 2 : i=1

Screen Shot 2014-06-18 at 3.25.55 PM

Fig 3 : i=2

Screen Shot 2014-06-18 at 3.26.57 PM

Fig 4 : i =2

Screen Shot 2014-06-18 at 3.29.25 PM

Fig 5 : i=3

Screen Shot 2014-06-18 at 3.32.47 PM

Fig 6 : i=3

Screen Shot 2014-06-18 at 3.35.19 PM

Fig 7 : i=4

Screen Shot 2014-06-18 at 3.37.45 PM

Fig 8 : i=4

Screen Shot 2014-06-18 at 3.42.22 PM

Fig 9 : i=5

Screen Shot 2014-06-18 at 3.44.58 PM

Fig 10 : i=5

Screen Shot 2014-06-18 at 3.47.25 PM

Fig 11 : i=6

Screen Shot 2014-06-18 at 3.50.03 PM

Fig 12 : i=6

 



Short URL: http://tinyit.cc/4d00f0
Author: Cusp2207 on June 18, 2014
Category: Computer Science
Tags:

Leave a Reply

Last articles