You are on page 1of 4

Prepared by Dr\Kadry Ali

1st method:
#include<iostream>
using namespace std;

int main(){
//declaring array
int array[5];
cout<<"Enter 5 numbers randomly : "<<endl;
for(int i=0; i<5; i++)
{
//Taking input in array
cin>>array[i];
}
cout<<endl;
cout<<"Input array is: "<<endl;

for(int j=0; j<5; j++)


{
//Displaying Array
cout<<"\t value at"<<j<<" Index: "<<array[j]<<endl;

}
cout<<endl;
// Bubble Sort Starts Here
int temp;
for(int i2=0; i2<=4; i2++)
{
for(int j=0; j<4; j++)
{
//Swapping element in if statement
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
// Displaying Sorted array
cout<<" Sorted Array is: "<<endl;
for(int i3=0; i3<5; i3++)
{
cout<<"\t\t value at"<<i3<<" Index:"<<array[i3]<<endl;
}
return 0;
}
2nd method is better than 1st method
2nd method:
#include<iostream>

using namespace std;

int main()
{
int a[50],n,i,j,temp;
cout<<"Enter the size of array: ";
cin>>n;
cout<<"Enter the array elements: ";

for(i=0;i<n;++i)
cin>>a[i];

for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

cout<<"Array after bubble sort:";


for(i=0;i<n;++i)
cout<<" "<<a[i];

return 0;
}

You might also like