Published on Oct 09,2014
699 Views
Email Post

Bubble sorting in C, also referred to as ‘Sinking Sorting’, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This is repeated until no swaps are needed, which indicates that the list is sorted. In Bubble sort, after every pass, the largest element moves to the end of the array.

## Example – Bubble Sorting in C:

Algorithm:

• Repeat until no elements are swapped
• For i=1 to n-1
• If a[i]<a[i-1] then swap (a[i], a[i-1])

```#include<stdio.h>
#define TRUE 1
#define FALSE 0
Void swap(int *arr, int index1, int index2)
Void bubblesort(int* a,int imin, int imax)
{
Int i;
Int swapped;
Do
{
Swapped = FALSE;
For(i=imin+1; i<=imax; i++)
{
If (a[i] < a[i-1])
{
Swap(a,i, i-1);
Swapped=TRUE
}
}
}while(swapped);
}
Void swap(int *arr, int index1, int index2)
{
Int temp;
Temp=arr[index1];
Arr[index1]=arr[index2]
Arr[index2]=temp;
}
Int main()
{
Int *arr=NULL;
Int num, key, loc, i;
Printf(“How many numbers:”);
Scanf(“%d”,&num);
Arr = (int*)malloc(num * sizeof(int));
Printf(“Enter the numbers:\n”);
For(i=0; i<num; i++)
{
Scanf(“%d”, &arr[i]);
}
Bubblesort(arr, 0, num-1);
Printf(“The sorted list:\n”);
For(i=0; i<num; i++)
{
Printf(“%d\n”, arr[i]);
}```

On compiling and running, the following output is obtained.

Let’s look at another example.

Got a question for us? Please mention them in the comments section and we will get back to you.

Related Posts:

C & Data Structures Training

Installation and Setting Up DevC Application

Introduction to C Programming – Algorithms

Understanding Structures and Padding in C