In this tutorial, You will learn about the bubble sort algorithm. Also, you will find complexity and example of bubble sort in C++ and Java.
Bubble sort is the data structure stable sorting algorithm. Bubble sort is the algorithm in which we compare two adjacent elements and swap elements in ascending or descending order.
Bubble Sort in Data Structure
In Bubble Sort, we can compare all elements one by one and sort one element at a time based on their value element.
Some few steps involved in the implementation of bubble sort are:
- You have to start from the value of the first element index i.e. index=0. Now, Compare the element with the adjacent next elements.
- If the first element is greater than the next element then swap both elements.
- And If the first element is less than the next element then move to the next element i.e. index=1 and repeat steps from step 1.
After each iteration of these 3 steps, the largest element of the unsorted elements placed at the end.
One by one each iteration one element is sort. so, we compare all elements upto the last unsorted elements.
Finally, when all unsorted elements are placed at their correct index then we can say elements are sorted.
![]() |
Compare adjacent elements |
![]() |
Compare adjacent elements |
Bubble Sort C++
//C++ program for Bubble Sort
#include<iostream>
using namespace std;
void bubbleSort(int arr[], int n);
// function declaration
int main()
{
int n, i;
// User have to enter number of elements to be sorted
cout<<"Enter Number of Elements to be Sorted :)";
cin>>n;
int arr[n];
// Input array elements
for(i = 0; i < n; i++)
{
cout<<"Enter element number: ";
cin>>arr[i];
}
// Call bubbleSort function
bubbleSort(arr, n);
return 0;
}
// function definition
void bubbleSort(int arr[], int n)
{
int pass, i, temp;
for(pass = 0; pass < n; pass++)
{
for(i = 0; i < n-pass-1; i++)
{
if( arr[i] > arr[i+1])
{
// Swap logic to swap the elements
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
// Print Sorted Array
cout<<"Sorted Array :) ";
for(i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
}
Output
Enter Number of Elements to be Sorted :)4
Enter element number: 3
Enter element number: 20
Enter element number: 10
Enter element number: 5
Sorted Array :) 3 5 10 20
--------------------------------
Happy Coding 😊
No comments:
If you have any doubts, Please let me know