What is Bubble Sorting?

What is Bubble Sorting?

Bubble Sorting is an algorithm where we try to swap the adjacent elements and arrange them in the correct order.

Let us see a real-time example and understand it more clearly.

In Amazon or FlipKart we see an option filter where we can arrange items according to the price which vary from low to high so that we can select the item accordingly and make a purchase.

So in the previous scenario, the items are getting arranged according to the price of the item which starts from a very low number and goes to a higher number, that is the numbers are compared with each other and the lowest number is swapped and pushed to the first place.

Let us see the coding part now:

#include<stdio.h>

void BubbleSort(int arr[], int n){
int i, j;

for(i = 0; i<n-1; i++) //outer loop checks the number of passes required to sort the array.
for(j=0;j<n-i-1;j++) //inner loop runs and checks for the elements and swaps the smallest element with the adjacent elements and puts the largest element at the end.

if(arr[j]>arr[j+1]){ //if the current element is larger than next element swap them
int temp = arr[j]; // if it is larger then the number achieved is stored in temp variable
arr[j]=arr[j+1]; //assign the smaller element to the current position
arr[j+1]=temp;//arrange the larger element to the next position
}
}
int main()
{
int i,n;

printf("Enter the size of array: ");
scanf("%d", &n);

int arr[n];

for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
BubbleSort(arr,n); //function call
printf("Sorted array: ");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}

}

Scroll to top