Friday, January 21, 2011

26.Bubble Sort


Bubble sorting is a simple sorting technique in sorting algorithm. In bubble sorting algorithm, we arrange the elements of the list by forming pairs of adjacent elements. It means we repeatedly step through the list which we want to sort, compare two items at a time and swap them if they are not in the right order. Another way to visualize the bubble sort algorithm is as its name, the smaller element bubble to the top. Here is the source code implements bubble sorting algorithm in C which sorts an unordered list of integer.

Step-by-step example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.
First Pass:
5 1 4 2 8 )  ->( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) ->( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
1 4 2 5 8 ) -> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) -> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.

Worst case performance= O(n2)
Best case performance =O(n)
Average case performance =O(n2)
Worst case space complexity =O(1) auxiliary




Bubble Sort Program:
#include<stdio.h> 
#include<conio.h>

void bubble(int a[],int n)
{
int i,j,t;
for(i=n-2;i>=0;i--)
{
for(j=0;j<=i;j++)

{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}


}//end for 1.

}//end function.


void main()
{

int a[100],n,i;

clrscr();

printf("\n\n Enter integer value for total no.s of elements to be sorted: ");
scanf("%d",&n);

for( i=0;i<=n-1;i++)
{
printf("\n\n Enter integer value for element no.%d : ",i+1);
scanf("%d",&a[i]);
}

bubble(a,n);

printf("\n\n Finally sorted array is: ");
for( i=0;i<=n-1;i++)
printf("%3d",a[i]);

} //end program




OUTPUT:
Enter integer value for total no.s of elements to be sorted: 6


Enter integer value for element no.1 : 89


Enter integer value for element no.2 : -4


Enter integer value for element no.3 : -67


Enter integer value for element no.4 : 5


Enter integer value for element no.5 : 78


Enter integer value for element no.6 : 11


Finally sorted array is: -67 -4 5 11 78 89




Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: