The Ins and Outs of Bubble Sorting
What is sorting?
It is the process of arranging data in a specific manner so that you can analyze it more effectively.
Type of Sorting
Selection Sort
Insertion Sort
Bubble Sort
Merge Sort
Quick Sort
heap Sort
Counting Sort
Radix Sort
In this article, we are going to learn Bubble sorting.
Bubble Sorting
let's take an array of n=5
In this sorting, we have to compare the neighbor element.
here there are (n-1) rounds to sort the whole array
beginning from the first round, in this, we have to place the largest element in the right place
As arr[1] is smaller than the arr[0] it shifts to the right side
and now same we have to do with the rest array
here we have successfully placed the largest element in it right place.
now Round -2
as we did in the round -1 we do same as in the round 2
As the arr[1] is smaller than the arr[2] here we ignore the jump.
now Round 3
now Round 4
develop a code on Bubble sorting
#include<iostream>
using namespace std;
//bubble sort
void bubble_sorting(int *arr,int n)
{
//base case
if(n<=1)
{
return;
}
for(int i=0;i<n-1;i++)
{
int j=i+1
if(arr[j]<arr[i])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
//recursive call
bubble_sorting(arr,n-1);
}
int main()
{
int arr[]={10,2,0,4,9};
int n=5;
bubble_sorting(arr,5);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
//output
0,2,4,9,10
Time Complexity
The time complexity of bubble sorting for the worst and the best case is given below
The worst case =O(n^2)
the best case = O(n)
Though it is easy to understand and implement, it is not efficient for sorting large arrays or lists. there are other sortings algorithm that are more efficient than the bubble sorting