Bubble Sort in C language

Bubble sort is the simplest Sorting algorithm available. It works by repeatedly swapping the adjacent or neighbor element if they are in the wrong order.

bubble sort algorithm program

Working

Actually in first pass bubble sort sets the largest element to its position, in the second pass algorithm sets the second largest element this continues till the list or array is not finally sorted.

Here is the example image.
working of bubble sort

To work with the algorithm you first have to understand what is swapping and how it is done.

What is Swapping ??

Swapping is the technique to interchange the content of the two variables, using another variable called temporary variable.

swapping example

For the program in C


#include <stdio.h>

void bubbleSort(int s[],int size){
int c,swap,d;
for (c = 0 ; c < size - 1; c++)
{
for (d = 0 ; d < size - c - 1; d++)
{
if (s[d] > s[d+1]) /* For decreasing order use < */
{
swap = s[d];
s[d] = s[d+1];
s[d+1] = swap; // swap is the temporary variable
}
}
}
// to print the array
for(c=0;c<size;c++){
printf("%d ",s[c]);
}
}
int main()
{
int x[100],c; // for security (if you wish you can increase size)
// taking the input from the user
printf("Please enter the number of element in an array: ");
scanf("%d",&c);
for (int i=0;i<c;i++){
printf("enter %d th number: ",i + 1 );
scanf("%d",&x[i]);
}

printf("before bubble sort \n");
for(int i=0;i<c;i++){
printf("%d ",x[i]);
}

printf("\n");
printf("After bubble sort \n");
bubbleSort(x,c);
printf("\n");
return 0;
}

that's all for this post.
if you have liked this post please subscribe and share the post.
Thanks for being here.

Comments

Popular posts from this blog

C/C++ program to check the Palindrome string.

Second Equation of motion, How to implement using C language

Third Equation of motion, How to implement using C language