UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C program to study 'Bubble Sort'

C program to understand bubble sort and how bubble sort works

Posted on 29 Aug 2017 Category: C Views: 929

Edited on 05 Sep 2017

C program to study 'Bubble sort'

Bubble sort algorithm implementation

Bubble sort works by swapping the adjacent elements if they are in wrong order. In this sorting mechanism , for the first pass it compares the adjacent elements and if b>a it swap (a,b).

For example, the elements need to be sorted are 3,2,1,5

For the first pass (3,2,1,5)è (2,3,1,5) swap (3,2)

(2,3,1,5)è(2,1,3,5) swap(3,1)

(2,1,3,5)è(2,1,3,5) no swapping

For the second pass , this swapping process repeats .

This swapping mechanism repeats until all the array elements are sorted.

Here is the C program to implement the Bubble sort algorithm.

``````#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int arr[100],i,j,n,temp=0;
printf(“enter the array limit :”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the element :”);
scanf(“%d”,&arr[i]);
}
for(i=0;i<n;i++);
{
for(j=0;j<n-1-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\n”);
for(i=0;i<n;i++)
{
printf(“\n %d”,arr[i]);
}
getch();
}

``````

• View all

• View all

• View all