Bubble sort is one of the simplest sorting technique. It compares two adjacent elements and swaps these if they are in the wrong order.

How to implement Buble Sort method using C++

For example, to sort an array of elements 3,1,2 in ascending order, bubble sort will compare the first pair of adjacent numbers 3 and 1. As 3 is greater than 1, these values will be swapped. The array will be 1,3,2. In the next iteration, 3 and 2 are compared and swapped again. The final result will be sorted array containing elements in the correct order.

C++ Code for Buble Sort 

#include <iostream>
using namespace std;

void BubbleSort (int arr[], int n){
	int i, j;
	for (i = 0; i < n; ++i)	{
		for (j = 0; j < n-i-1; ++j)		{

			if (arr[j] > arr[j+1])			{
				arr[j] = arr[j]+arr[j+1];
				arr[j+1] = arr[j]-arr[j + 1];
				arr[j] = arr[j]-arr[j + 1];
			}
		}
	}
}

int main(){
    int n =7;
    int arr[n] = {4, 2, 1, 6, 5, 9, 0};
	BubbleSort(arr, n);
	cout<<"\nSorted Data ";
	for (int i = 0; i < n; i++)
             cout<<"  "<<arr[i];
             cout<<endl;
             return 0;
}

Related Articles

Last modified: October 29, 2019

Comments

Write a Reply or Comment

Your email address will not be published.