PoiNtEr->: Bubble Sort (Working in Best Case)

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Tuesday, January 11, 2011

Bubble Sort (Working in Best Case)


Do U really know How Bubble Sort Work ???

Well in most of the books algorithm given for bubble sort is wrong

because it dont work for best case of bubble sort

Here i am providing you correct one:

Points to remember:

1:after every iteration in bubble sort highest value element get sorted(if we are sorting in ascending order otherwise vise-versa)

2:That means after first iteration we compare only n-1 element if we started with n elements.

3:We compare adjacent elements(do rememberSort element sorted are not compared ),if order is wrong then we swap them.

3:best case complexity of bubble sort is O(n),that if we give already sorted element as input then bubble sort will take only O(n)

4:Average case and Worst case Complexity O(n^2).

void bubble(int a[],int n)

{

int temp,j,pass;

int s=1;

for(pass=0;pass<n-1 && s=1;pass++)

/* outer loop control no. of pass */

{

s=0; /* initially no interchange had been made */

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

{

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

{

/* element not in order need to be interchange to achieve our goal of sorting */

s=1;

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}/* end of if */

}/* end of inner loop for */

}/* end of outer loop */

}/*end of bubble */

/* have any problem feel free 2 ask*/

No comments:

Post a Comment