/********************************************************\
* *************** ************** *
* * * BUBBLE SORT * * *
* *************** ************** *
/********************************************************/
#include <iostream.h>
#include <conio.h>
#include <malloc.h>
void bubble_sort(int a[], int n);
void main()
{
int i,n;
int* a;
clrscr();
cout << "Enter the no. of elements:";
cin >> n;
a = (int*) malloc(sizeof(int)*n); //dynamic array declearation
cout << "\nEnter the elements :\n\n";
for(i = 0; i < n; i++)
{
cin >> a[i];
}
bubble_sort(a, n);
cout << "\nSorted array is: ";
for(i = 0; i < n; i++)
{
cout << a[i] << " ";
}
getch();
}
void bubble_sort(int a[], int n)
{
int i,j,temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
Output :
No comments:
Post a Comment