bubble sort – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 04 Jul 2022 06:11:46 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg bubble sort – Programmerbay https://programmerbay.com 32 32 C program to sort an array using Bubble Sort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/ https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/#respond Wed, 10 Jun 2020 10:56:44 +0000 https://www.programmerbay.com/?p=2867 The program sorts an array in ascending order based on the given input. There are various sorting algorithms to achieve this functionality Such as Selection Sort, Insertion sort and more . In this, We’ll be using Bubble Sort algorithm.

Bubble sort is one of the simplest and most popular algorithms, but inefficient. It repeatedly compares each element with their adjacent elements and performs swapping if required.

Pseudocode

FOR i=0 to Array.Length
FOR j=Array.Length-1 to i
IF A[j]< A[j-1])
Swap A[j] and A[j-1]
END IF
END FOR
END FOR

C program to sort an array using Bubble Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<=size-1;i++)
{
for(j=size-1;j>i;j--)
{
if(arr[j]<arr[j-1]){
temp = arr[j];
arr[j] =arr[j-1];
arr[j-1] = temp;
}

}

}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

 

Output:

bubble sort 1

How does Bubble Sort program work?

bubble sort working

It requires a constant amount O(1) of additional memory space and O(n2) comparisons in the worst case and average case to sort an array.

However, this sorting technique is too slow and impractical if we compare it with Insertion sort

]]>
https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/feed/ 0