In this lecture we showed an example of C++ function that implements the bubble sort algorithm, we also add complete C++ code for bubble sort algorithm without the function.
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This algorithm is named as bubble sort because, in this sort, the smaller value like a bubble comes up to the top position.
The basic idea behind bubble sort is to repeatedly compare adjacent elements in a list and swap them if they are in the wrong order. This process repeats until the list is sorted. Bubble sort has a time complexity of O(n^2) which makes it inefficient for sorting large data sets.
Despite its inefficiency, bubble sort is still used in some cases because of its simplicity and ease of implementation. It is particularly useful for small data sets or for educational purposes to illustrate how the sorting algorithm works.
You can also learn Selection Sort and Insertion Sort Algorithm from here.
Code explanation
- We have used two for loop. The first one is to iterate the loop for Array element i=0 to size-1 to sort the highest value at the position at the right end of the array list.
- And the second for loop is to compare the array element to each other to set the position according to its value.
Complexity Analysis
- Runtime complexity is O(n^2).
- Space Complexity is O(1). We just use a constant-size Array. We did not change the Array size. It means constant space required to run the code.
Bubble Sort With Function
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
This function takes an array arr
and its size n
as arguments, and sorts the elements of the array in ascending order using the bubble sort algorithm.
The function works by repeatedly iterating through the array, comparing adjacent elements and swapping them if they are in the wrong order. This process is repeated until the array is sorted.
Note that the bubble sort algorithm is not the most efficient sorting algorithm, as it has a time complexity of O(n^2) in the worst case. However, it is simple to implement and can be useful for small arrays or as a learning exercise.
Bubble Sort Without Function
Here is the Complete code.
#include<iostream>
using namespace std;
int main()
{
int Array[] = {1,5,2,9,8,7,3};
int i, j, Size = 7;
for(i=0; i<Size-1; i++)
{
for(j=0; j<Size-1; j++)
{
//swap first two numbers.
if(Array[j]>Array[j+1])
{
int temp;
temp = Array[j];
Array[j]=Array[j+1];
Array[j+1]=temp;
}
}
}
cout<<"After Sorting: ";
for(i=0; i<Size; i++)
{
cout<<Array[i]<<' ';
}
return 0;
}