Bubble sort algorithm:
This is a bubble sort function that receives a Data array and n-th elements.
BubbleSort ( DataArray, n)
Step 1: Declare the needed variable for the 'for' loop iterations.
Step 2: Repeat step 3 and 4 for i = 1 to n-1.
Step 3: Set ptr=1. [ Initialising of ptr]
Step 4: Repeat while ptr<= n - i : [ One can execute a for loop instead of while loop ]
(a) if DataArray[ptr+1] < DataArray [ptr]
Interchange the DataArray[ptr] and DataArray [ptr+1] using a temp variable.
[ End of structure ]
(b) Set ptr = ptr+1
[ End of while or for loop ]
[ End of step 1 function loop]
Step 5: Exit of the program
Bubble sort program in c++ :
Step 1: first of all, to take input and give output in the program, the process has been discussed for the other sorting algorithms in this blog. please read others (Insertion sort) sorting implementation.
Input:
int n, i, j, temp;
cin>>n;
int DataArray[n];
for (i=1; i<=n; i++)
{
cin>>DataArray[I];
}
Output:
for (i=1; i<=n; i++)
{
cout<<DataArray[i]<<" ";
}
Step 2: Here the main function will be discussed. As told in the algorithm, we have to take a temp variable and will compare the n-th item with (n-1)-th item for the sorting. And here is the logic and swapping process between the Array and temp variables.
for (i=1; i<=n; i++)
{
for (j=1; j<n; j++)
{
if (DataArray[j+1] < DataArray[j])
{
temp = DataArray[j];
DataArray[j] = DataArray[j+1];
DataArray[j+1] = temp;
}
}
}
Step 3: The above algorithm and code are for the ascending order sorting. For the descending order sorting, we have a change in the if the loop of the inner for loop.
for (i=1; i<=n; i++)
{
for (j=1; j<n; j++)
{
if (DataArray[j+1] > DataArray[j])
{
temp = DataArray[j];
DataArray[j] = DataArray[j+1];
DataArray[j+1] = temp;
}
}
}
Step 4: Now, the full program of bubble sort in c++.
#include<iostream>
using namespace std;
int main()
{
int n, i, j, temp;
cin>>n;
int DataArray[n];
for (i=1; i<=n; i++)
{
cin>>DataArray[i];
}
for (i=1; i<=n; i++)
{
for (j=1; j<n; j++)
{
if (DataArray[j+1] < DataArray[j])
{
temp = DataArray[j];
DataArray[j] = DataArray[j+1];
DataArray[j+1] = temp;
}
}
}
for (i=1; i<=n; i++)
{
cout<<DataArray[i]<<" ";
}
return 0;
}
Sample Input:
5
5 3 1 4 2
Sample Output:
1 2 3 4 5
Ok. Bubble sort can be sorted also using the c++ built-in function. The code is below.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, i, j, temp;
cin>>n;
int DataArray[n];
for (i=0; i<n; i++)
{
cin>>DataArray[i];
}
sort(DataArray, DataArray+n);
for (i=0; i<n; i++)
{
cout<<DataArray[i]<<" ";
}
return 0;
}