Professional Documents
Culture Documents
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;
}
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>
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;
}
}
return 0;
}