Bubble Sort in C++

Bubble sort is the simplest sorting algorithm. It works by comparing the adjacent elements of the array. It swaps both the elements if they are not in order.

The algorithm is shown below.

/*
 * Bubble Sort
 */
#include<iostream>
using namespace std;
void print(int a[],int n){
	cout<<"The elements of array are "<<endl;
	for(int i=0;i<n;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
}
void swap(int& a,int& b){
	int temp;
	temp = a;
	a = b;
	b = temp;
}
void bubble_sort(int a[],int n){
	for(int i=1;i<n;i++){
		for(int j=0;j<n-1;j++){
			if(a[j]>a[j+1])swap(a[j],a[j+1]);
		}
	}
}
int main(){
	int a[] = {20,10,30,45,85,23,78};
	int size = sizeof(a)/sizeof(int);
	print(a,size);
	bubble_sort(a,size);
	print(a,size);
	return 0;
}
sorted elements using bubble sort
sorted elements using bubble sort

Try the same using

  • Selection Sort
  • Insertion Sort
  • Merge Sort
  • Quick Sort
  • Heap Sort
  • Radix Sort
  • Shell Sort

Leave a Reply