Search here

Pages

Saturday, August 13, 2011

Bubble Sorting

Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better.

Performance:

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. There exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n). Even other О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort. Therefore, bubble sort is not a practical sorting algorithm when n is large.
                     The only significant advantage that bubble sort has over most other implementations, even quicksort, but not insertion sort, is that the ability to detect that the list is sorted is efficiently built into the algorithm. Performance of bubble sort over an already-sorted list (best-case) is O(n). By contrast, most other algorithms, even those with better average-case complexity, perform their entire sorting process on the set and thus are more complex. However, not only does insertion sort have this mechanism too, but it also performs better on a list that is substantially sorted (having a small number of inversions).

An Animated Example:



Program for Bubble sort compiled and executed in turbo C++  
#include<iostream.h>
#include<conio.h>
void swap(int &,int &);
void main()
{
int a[30],i,j,k;
clrscr();
cout<<"Enter the No of elements yo want to enter";
cin>>k;
cout<<"Now enter elements";
for(i=0;i<k;i++)
cin>>a[i];
for(i=0;i<k;i++)
{
for(j=0;j<k-i;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
cout<<"The sorted order is";
for(i=0;i<k;i++)
cout<<a[i]<<"\t";
getch();
} 
Buuble Sort-Overview
Class Sorting algorithm
Data structure Array
Worst case performance O(n2)
Best case performance O(n)
Average case performance O(n2)
Worst case space complexity O(1) auxiliary


0 comments

Post a Comment