Algorithm Series - 1 | Bubble Sort
Intro
Competition programming is a field that generally involves the host presenting a set of logical or mathematical problems to the contestants , a field that I'm good at. I've participated in many high school and college contest like the International Olympiad of Informatics and won some medals. So I decided to contribute some of my knowledge to HF and I wasn't sure where to start the series Coding and Programming or C/C++/Obj-C Programming. Since I will be implementing the algorithms in C++ I will start it in this section. Notice I have some limitations because of my low post count.
Bubble Sort
A simple sorting algorithm.The bubble sort algorithm compares every two items which are next to each other, and swaps them if they are in the wrong order. An array of n elements can be sorted within n-1 passes. For example, in this array of 4 items:
First pass:
(4, 3, 1, 2) → (3, 4, 1, 2)
(3, 4, 1, 2) → (3, 1, 4, 2)
(3, 1, 4, 2) → (3, 1, 2, 4)
Second pass:
(3, 1, 2, 4) → (1, 3, 2, 4)
(1, 3, 2, 4) → (1, 2, 3, 4)
(1, 2, 3, 4) → (1, 2, 3, 4)
Third pass:
(1, 2, 3, 4) → (1, 2, 3, 4)
(1, 2, 3, 4) → (1, 2, 3, 4)
(1, 2, 3, 4) → (1, 2, 3, 4)
Implementation in C++
PHP Code
<?php
//Algorithm Series 1 - Bubble Sort
//Deadbyte
#include<iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the number of elements of the array: ";
cin >> n;
int ar[n];
cout << "Enter the elements of the array: ";
for(int i=0;i<n;i++)
{
cin >> ar[i];
}
int tmp;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
if(ar[i]>ar[j])
{
tmp=ar[i];
ar[i]=ar[j];
ar[j]=tmp;
}
}
cout << "The sorted array is: " << endl;
for(int i=0;i<n;i++)
{
cout << ar[i] << " ";
}
system("pause");
return 0;
}
Code analysis
PHP Code
<?php
// Declaration and input
int n;
cout << "Enter the number of elements of the array: ";
cin >> n;
int ar[n];
cout << "Enter the elements of the array: ";
for(int i=0;i<n;i++)
{
cin >> ar[i];
}
We declare the variable ar which is the array.
With a loop we enter the elements of the array , a loop that iterates n times.
PHP Code
<?php
//Swapping the elements
int tmp;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
if(ar[i]>ar[j])
{
tmp=ar[i];
ar[i]=ar[j];
ar[j]=tmp;
}
}
PHP Code
<?php
//Output
cout << "The sorted array is: " << endl;
for(int i=0;i<n;i++)
{
Thank you for reading. I hope the series will help the beginners in competition programming.


![[Image: dead.gif]](https://image.ibb.co/gSF95a/dead.gif)
