Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

cpp bubble sort

//HOW ABOUT MORE EFFICIENT SOLUTION
//  BASIC IDEA- REPEATEDLY SWAP TWO ADJACENT ELEMENTS IF THEY ARE IN A WRONG ORDER.
#include<bits/stdc++.h>
using namespace std;
void bubblesort(int a[], int n)
{
	bool swapped=false;
	for(int i=0;i<n-1;i++)
	{
		for(int j=0;j<n-i-1;j++)
		{
			if(a[j]>a[j+1]) // check if ADJACENT elements are in a wrong order.
			{
				swap(a[j],a[j+1]); //if they are swap them.
				swapped=true;
			}
		}
		if(swapped==false) break; // if for any particular iteration our array doesn't swap--
        // -- any numbers then we may conclude that our array has already been sorted. :)
	}
}
int main()
{
	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++) cin>>a[i];
	bubblesort(a,n);
	for(int i=0;i<n;i++) cout<<a[i]<<" ";
	return 0;
}
	
Source by codescracker.com #
 
PREVIOUS NEXT
Tagged: #cpp #bubble #sort
ADD COMMENT
Topic
Name
3+8 =