Bubble sort

Sorting

Sorting is a process in which we arrange the data of  any list in any particular order  such as ascending order and descending order.




Bubble sort

 Bubble sort is oldest and slow sorting technique. In this technique first element is compared with second element, second element is compared  with third element, third element is compared with fourth element and so on. This process is repeated till the data is sorted.  
for example:-
10
5
8
3
2
4
in this list 0th element is compare with 1st element  and 1st element is compare with 2nd element and so on till the data is sorted.


Example of bubble sort.  


1st itration.

step=1

      a[0]>a[1]   true
      swap( a[0],a[1])
        a[0]=5;
        a[1]=10;
step=2
      a[1]>a[2]   true
      swap( a[1],a[2])
        a[1]=8;
        a[2]=10;
step=3
      a[2]>a[3]   true
      swap( a[2],a[3])
        a[2]=3;
        a[3]=10;
step=4
      a[3]>a[4]   true
      swap( a[3],a[4])
        a[3]=2;
        a[4]=10;
step=5
      a[4]>a[5]   true
      swap( a[4],a[5])
        a[4]=4;
        a[5]=10;
5
8
3
2
4
10

2st itration.
step=1
      a[0]>a[1]   false
          5>8;
step=2
      a[1]>a[2]   true
      swap( a[1],a[2])
        a[1]=3;
        a[2]=8;
step=3
      a[2]>a[3]   true
      swap( a[2],a[3])
        a[2]=2;
        a[3]=8;
step=4
      a[3]>a[4]   true
      swap( a[3],a[4])
        a[3]=4;
        a[4]=8;
5
3 2 4 8
10

3st itration.

step=1
      a[0]>a[1]   true
          swap(a[0],a[1];
           a[0]=3;
          a[1]=5;
step=2
      a[1]>a[2]   true
      swap( a[1],a[2])
        a[1]=2;
        a[2]=5;
step=3
      a[2]>a[3]   true
      swap( a[2],a[3])
        a[2]=4;
        a[3]=5;
3 2 4 5 8
10


4st itration.

step=1

      a[0]>a[1]   true
          swap(a[0],a[1];
           a[0]=2;
          a[1]=3;
step=2
      a[1]>a[2]   false
2 3 4 5 8
10

       

5st itration.

step=1

      a[0]>a[1] 
         flase

now all condition is false and data is sorted in ascending order, finally result is that-
2 3 4 5 8
10

Inplementation of bubble sort program


void bubble_sort(int a[],int size)
{

    int i,j,temp;
    for(i=0;i<size-1;i++)
    {
        for(j=0;j<size-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
    printf("All record in ascending order\n");
    for(i=0;i<size-1;i++)
    {
        printf("%d\n",a[i]);
    }
}



thanku..........
like my facebook page   


Comments

Popular posts from this blog

python pattern programming

Decision making statement in python

javaScript Calculator.