2021-01-12 07:49:46 +00:00
|
|
|
//bubble sort
|
|
|
|
# include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
cout<<"Enter the length of array"<<endl;
|
|
|
|
int m, temp,n;
|
|
|
|
cin>>n;
|
|
|
|
int arr[n];
|
|
|
|
cout<<"Enter the elements of array"<<endl;
|
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
{ //array elements input
|
|
|
|
cin>>arr[i];
|
|
|
|
}
|
2021-05-15 18:14:44 +00:00
|
|
|
bool swap;
|
2021-01-12 07:49:46 +00:00
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
{
|
2021-05-15 18:14:44 +00:00
|
|
|
swap = false;
|
2021-01-12 07:49:46 +00:00
|
|
|
for (int j= 0; j< n-1; j++)
|
|
|
|
{ //comparing adjecent elements of array
|
|
|
|
if (arr[j]>arr[j+1])
|
2021-04-10 09:10:32 +00:00
|
|
|
{ // swapping array elements
|
2021-01-12 07:49:46 +00:00
|
|
|
temp = arr[j];
|
|
|
|
arr[j] = arr[j+1];
|
|
|
|
arr[j+1] = temp;
|
2021-05-15 18:14:44 +00:00
|
|
|
swap = true;
|
2021-01-12 07:49:46 +00:00
|
|
|
}
|
|
|
|
}
|
2021-05-15 18:14:44 +00:00
|
|
|
|
|
|
|
// break if no swap takes place in inner loop
|
|
|
|
// it means the array is sorted
|
|
|
|
if(!swap){ break; }
|
2021-01-12 07:49:46 +00:00
|
|
|
}
|
|
|
|
for (int i = 0; i < n; ++i)
|
|
|
|
{
|
|
|
|
cout<<arr[i]<<" ";
|
|
|
|
}
|
|
|
|
return 0;
|
2021-04-10 09:10:32 +00:00
|
|
|
}
|