Bubble Sort


1. Bubble Sort

The simplest sorting algorithm is bubble sort. The bubble sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted. Since the worst case scenario is that the array is in reverse order, and that the first element in sorted array is the last element in the starting array, the most exchanges that will be necessary is equal to the length of the array. Here is a simple example: 

Ex Bubble Sort

2. Source Code:

#include<math.h>
#include<iostream>
#include<conio.h>
#define max 100
using namespace std;

//Input Array
void InputArray(int A[],int n){
for(int i=0; i<n; i++) {
cout<<"Input element A["<<i<<"] =";
cin>>A[i];
}
}

//Print Array
void PrintArray(int A[],int n){
cout<<endl;
for(int i=0; i<n; i++)
cout<<A[i]<<"\t";
}

//Swap 2 elements
void Swap(int &a,int &b){
int temp = a;
a = b;
b = temp;
}

//Sorting by BubbleSort
void BubbleSort(int A[],int n){
for(int i = 0; i < n-1; i++)
for(int j = n-1; j > i; j--)
if(A[j]<A[j-1])
Swap(A[j-1],A[j]);
}

//Main function
int main(){
int A[max],n;
cout<<"Input number of array:";
cin>>n;
InputArray(A,n);
cout<<"\nOriginal Array:";
PrintArray(A,n);
cout<<endl;
BubbleSort(A,n);
cout<<"\nSorted Array:";
PrintArray(A,n);
getch();
return 0;
}

3. Result:

bubble sort-result

 


Advertisements