A blog to help students to learn programming in various languages including C, C++, Java, Python and many more.

Subscribe For Free Latest Updates!

We'll not spam mate! We promise.

Saturday 16 January 2016



Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps 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, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position.

Performance:->

  • Best case: O(n)
  • Average case: О(n2)
  • Worst case: О(n2)

Information source: wikipedia.org


Program:->

Program Output
Output
#include <iostream>
using namespace std;
int bubble(int *ptr,int n);
int main()
{
int n,data,a[100];
int *ptr;
ptr=a;
cout<<"Enter no. of values: ";
cin>>n;
cout<<"Enter "<<n<<" values: ";
for(int x=0;x<n;x++) {
cin>>*(ptr+x);
}
bubble(ptr,n);
cout<<"Array after Sorting using BUBBLE Sort: \n";
for(int x=0;x<n;x++) {
cout<<*(ptr+x)<<"\n";
}
return(0);
}
int bubble(int *ptr,int n)
{
int x,temp;
for(int k=0;k<n;k++) {
x=0;
while(x<n-k-1) {
if(*(ptr+x)>*(ptr+x+1)) {
temp=*(ptr+x+1);
*(ptr+x+1)=*(ptr+x);
*(ptr+x)=temp;
}
x=x+1;
}
}
}


0 comments :

Post a Comment



Copyright © 2016 - ProgrmIt - All Rights Reserved
(Articles Cannot Be Reproduced Without Author Permission.)
Design By : | Powered By: Blogger