Bubble Sorting In c Language

Keep In Mind:-

1. If there are N number of unsorted elements then N-1 number of iteration.
2. Start comparison from left to right.
3. Do comparison only with adjacent  elements (left to right).
4. T(n) = O(n2)    (worst case)
5. Best case : O(n)
6. Average case : O(n2).


Basic Idea:-

Given elements in an array: - 2,4,1,5,3,7.

Step 1- Choose 2 and compare with 4  =  2,4  (2<4 no swapping).
                   "     4   "        "           "     1=   2,1,4  (4>1  swaping done)
                    "     4   "         "         "     5=   2,1,4,5  (4<5  no swapping)
                    "      5   "         "        "      3 = 2,1,4,3,5    (5>3  swappin done)
                    "      5    '         "        "      7  = 2,1,4,3,5,7  after first iteration.

do same for second and third iteration till all elements not sorted.

After sorting : 1,2,3,4,5,7


Algorithms:

 Bubble sort (A,n)   
{
      for k=1 to n-1
           {
               for i=0  to n-1
             { 
                  if( A[i] > A[i+1] )
                 {
                    swap( A[i], A[i+1] )
                  }
              }
           }
   }


Coding :-

#include<stdio.h>
#include<conio.h>
int main()
{

  int s,temp,i,j,a[100];

  printf("Enter numbers of elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);

  //Bubble sorting algorithm
  for(i=s-2;i>=0;i--){
      for(j=0;j<=i;j++){
           if(a[j]>a[j+1]){
               temp=a[j];
              a[j]=a[j+1];
              a[j+1]=temp;
           }
      }
  }

  printf("After sorting: ");
  for(i=0;i<s;i++)
      printf(" %d ",a[i]);

  return 0;
}


Output:

Enter total numbers of elements: 5
Enter 5 elements: 6 2 0 11 9
After sorting:  0 2 6 9 11  

Comments

Popular posts from this blog

Design a Calculator Using C# code.

CONVERSION INTO BINARY FROM DECIMAL, HEXA, OCTAL NUMBERS

Insertion Sorting in C Language.