What is Bubble sort and example In C++


In this program we will write a program which sorts an array of numbers using a famous bubble sort algorithm. This algorithm uses a “swap” function which swaps values stored in two memory locations with each other. Bubble sort compares each two cells of the array and if they are not in correct order, it swaps them. If we need the array to be sorted in ascending order, each cell should be bigger or equal to previous cell and the first cell should be smaller than any other cell. If we perform these compares and swaps for “n- 1” times on the entire array, our array will be completely sorted.

Bubble sort example In C++

#include<stdio.h> void swap(int *a,int *b); main() { int ar[5],i,j,n; ar[0]=7;ar[1]=3;ar[2]=9;ar[3]=2;ar[4]=11; cout<<Array before sort:\n\n for(i=0;i<5;i++) cout<<"ar[%d]=%d\n",<<i,ar[i] n=5; /*numberof items in sort array*/ for(i=0;i<n-1;i++) for(j=0;j<n-1;j++) { if(ar[j]>ar[j+1]) swap(&ar[j],&ar[j+1]); } printf("Array after sort:\n\n"); for(i=0;i<5;i++) cout<<"ar[%d]=%d\n",<<i,ar[i] return 0; } void swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; }