March 18, 2018

Sorting Array - Bubble Sort

Bubble Sort:-
If elements being arranged in increasing order with this technique, then largest element reaches first at its correct position,then second largest and so on.

And if elements being arranged in decreasing order,then smallest element reaches first at its correct position,then second smallest and so on.

This technique is used when we first want the element that should be at the last position of the array after being sorted.
Explanation:

This technique sort in bubbles that means small parts are checked are sorted

Step 1:
In first pass,
5 and 2 are compared, not sorted ,so swapped.
Then 5 and 3 are compared, not sorted ,so swapped.
Then 5 and 1 are compared, not  sorted, so swapped.
Then 5 and 4 are compared, not  sorted, so swapped.
 Now largest element i.e. 5 has attained its correct position.


When i=0 then n-0-1 i.e. 4 times testing operation is performed. Here element whose position should be x[4] is obtained.

Step 2:
In second pass,
2 and 3 are compared, sorted ,not swapped.
Then 3 and 1 are compared, not sorted ,so swapped.
Then 3 and 4 are compared, sorted, not swapped.
 Now largest element i.e. 4  has attained its correct position.

When i=1 then n-1-1 i.e. 3 times testing operation is performed.
Here element whose position should be x[3] is obtained.

Step 3:
In third pass,
2 and 1 are compared, not sorted ,so swapped.
Then 2 and 3 are compared, sorted ,not swapped.
Now third largest element i.e. 3  has attained its correct position.

When i=2 then n-2-1 i.e. 2 times testing operation is performed.
Here element whose position should be x[2] is obtained.

Step 4:
In forth pass,
1 and 2 are compared, sorted ,not swapped.
Now forth largest element i.e. 2  has attained its correct position.

When i=3 then n-3-1 i.e. 1 time testing operation is performed.
Here element whose position should be x[1] is obtained.

Step 5:
In fifth pass,
No comparisons are left.
Fifth largest element is at its correct position.

 When i=4 then n-4-1 i.e. 0 time testing operation is performed.
 Here element whose position should be x[0] is obtained.



Code:

#include<stdio.h>

void main()

{

 int x[5]={5,2,3,1,4};

 int i,j,temp,n=5;

 printf("\nList of elements");

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

  printf("\n%d",x[i]);


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

  {

   for(j=0;j<n-i-1;j++)

   {

    if(x[j] > x[j+1])

    {

     //swap them

     temp=x[j];

     x[j]=x[j+1];

     x[j+1]=temp;

    }

   }

  }


 printf("\nAfter Sorting");

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

  printf("\n%d",x[i]);


  getch();

}

Output:


No comments:

Post a Comment