bubble sort cpp code example
Example 1: bubble sort in c++
void bubble_sort( int A[ ], int n ) {
int temp;
for(int k = 0; k< n-1; k++) {
for(int i = 0; i < n-k-1; i++) {
if(A[ i ] > A[ i+1] ) {
temp = A[ i ];
A[ i ] = A[ i+1 ];
A[ i + 1] = temp;
}
}
}
}
Example 2: bubble sort c++ template
template < typename T > void bubble_sort( T a[], int n )
{
int i,j;
T temp ;
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
Example 3: code for bubble sort in c++
void bubbleSort (int S[ ], int length) {
bool isSorted = false;
while(!isSorted)
{
isSorted = true;
for(int i = 0; i<length; i++)
{
if(S[i] > S[i+1])
{
int temp = S[i];
S[i] = S[i+1];
S[i+1] = temp;
isSorted = false;
}
}
length--;
}
}
Example 4: Bubble Sort C++
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int n,temp,c=0;
cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
c++;
}
}
if(c==0)
{
break;
}}
cout<<"Array is sorted in "<<c<<" swaps."<<endl;
cout<<"First Element:"<<" "<<a[0]<<endl;
cout<<"Last Element:"<<" "<<a[n-1]<<endl;
return 0;
}
Example 5: bubble sort program in c++
cout<<"\n Hello World ";