Bubble Sort in C++ with UDF (For CBSE - XII)

//Bubble Sort with UDF
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<iomanip.h>
void BubbleSort(int [], int);
const int size=50;

void main()

{
int a[size], n, i;
clrscr();
cout<<"\nEnter the  size of array you want (Max. "<<size<<"): ";
cin>>n;

randomize();

for(i=0;i<n;i++)
{
a[i]=random(80)+20;
}

cout<<"\nThe array elements are : ";

for(i=0;i<n;i++)
cout<<setw(5)<<a[i];
cout<<endl;

BubbleSort(a,n);


cout<<"The sorted array elements are : ";

for(i=0;i<n;i++)
cout<<setw(5)<<a[i];
cout<<endl;
getch();
}

void BubbleSort(int a[], int n)

{
int i, j, tmp;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
cout<<"\nAfter step-"<<setw(2)<<j+1<<": ";
if(a[j]>a[j+1])
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
for(int k=0;k<n;k++)
cout<<setw(5)<<a[k];
}
cout<<endl;
}
}

/*

Output
Enter the  size of array you want (Max. 50): 6

The array elements are :    87   70   39   94   59   25


After step- 1:    70   87   39   94   59   25

After step- 2:    70   39   87   94   59   25
After step- 3:    70   39   87   94   59   25
After step- 4:    70   39   87   59   94   25
After step- 5:    70   39   87   59   25   94

After step- 1:    39   70   87   59   25   94

After step- 2:    39   70   87   59   25   94
After step- 3:    39   70   59   87   25   94
After step- 4:    39   70   59   25   87   94

After step- 1:    39   70   59   25   87   94

After step- 2:    39   59   70   25   87   94
After step- 3:    39   59   25   70   87   94

After step- 1:    39   59   25   70   87   94

After step- 2:    39   25   59   70   87   94

After step- 1:    25   39   59   70   87   94


The sorted array elements are :    25   39   59   70   87   94

*/

No comments

Post your comments

Powered by Blogger.