OneCompiler

Bubble sort algorithm

154

#include <iostream>
using namespace std;

int main()
{
int n;
cin>>n;

int a[n],i;

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

// bubble sort algorithm

int counter = 1; // for performing no. of iterations

while(counter<n)
{

  for(i=0; i<n-counter; i++)
  {
    if(a[i]>a[i+1])  // in ascending // a[i+1]>a[i]  for descending
    {
     int temp=a[i];
      a[i]=a[i+1];
      a[i+1]=temp;
    }
  }
counter++;

}

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

return 0;

}