Understanding the Bubble Sort Algorithm in C++
Sorting is one of the basic operations in programming, and one of the simplest sorting algorithms is Bubble Sort. Following is a simple implementation of the Bubble Sort algorithm that will sort an array of integers in ascending order.
Code:
#include<iostream>
using namespace std;
int main(){
int arr[] = {17,2,12,4,9,5,10};
int n = sizeof(arr)/sizeof(int);
int temp;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"Ascending order: ";
for(int i = 0; i < n; i++){
cout<<arr[i]<<" ";
}
}
Code Explanation:
- Header Files

#include<iostream>: This library is used for input and output operations like cin and cout.
2. Main Function

Array Initialization:
arr[] – array holding integers to be sorted.
sizeof(arr)/ sizeof(int) gives total no. of elements in the array i.e. ‘n’.
Auxiliary temporary array ‘temp’
Used for swapping the elements in case during implementation of sorting

Outer loop -i
To travel the array to complete assurance about sorting
In-loop -j
The j compares each element that stands next to one another, then performs the swapping action if the adjacent are out of order (arr [j] > arr [j + 1]). Once again repeats these processes and this manner “bubbles up” largest element into proper place in every cycle.
Sort array in ascending order
The sorted array:

After the excecution of this loop, array is sorted in ascending order.
Key Concepts in the Program
Bubble Sort:
A basic sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
Swap Elements:
The operation of two variables trading values, usually using a temporary variable.
Nested Loops:
While the inner loops are doing the work of compare-in-pairs, it is the outer loops that ensure that all elements will bubble into their final position.
Bubble Sort Efficiency
Time Complexity:
Worst Case: O(n²) when the array is reverse-sorted.
Best Case: O(n) when the array is already sorted, with slight optimization.
Space Complexity:
O(1) because no additional space is used other than the input array.
Why Bubble Sort is Suitable for Beginners ?
Easy to Comprehend: The logic is very simple and easy to understand.
Learning Aid: Assists novice programmers in understanding the concepts of sorting and nested loops.
Common in Educational Use This is one of the standard algorithms used in introductory programming classes.