Tuesday, July 10, 2018

Program 13


BUBBLE SORT
Write a C++ program to accept a single dimensional array and sort given array elements by Bubble Sort.
                                               
#include<iostream.h>
#include<conio.h>
void bubblesort(int[],int);
void main()
{
clrscr();
int a[50],item,n,index;
cout<<"Enter array size ";
cin>>n;
cout<<"\nEnter array elements :";
for(int i=0;i<n;i++)
cin>>a[i];
bubblesort(a,n);
cout<<"\n\nThe sorted array is as shown below \n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
getch();
}

void bubblesort(int a[],int size)
{
int tmp,ctr=0;
for(int i=0;i<size;i++)
{
for(int j=0;j<(size-1)-i;j++)
{
if(a[j]>a[j+1])
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
cout<<"\nArray after iteration - "<<++ctr<<" - is:";
for(int k=0;k<size;k++)
cout<<a[k]<<" ";
cout<<endl;
}
}

No comments:

Post a Comment