Pages

This blog is under construction

Tuesday, January 8, 2019

C program for Bubble Sort

Bubble sort starts by comparing the first and second element of the array and swaps their positions if necessary (depending on whether the sort order is ascending or descending). Next, it will compare the second and third element and swaps them if needed. This is continued upto the last element of the array and then the iteration starts again from the first element to last. If no elements are swapped in an iteration then it means the array is fully sorted and the iteration ends. Each iteration or pass of bubble sort from first to last element will move one element to its correct location in the array just like a bubble rising up in water.

C Program

#include<stdio.h>
void main()
{
int n, i, j, temp;
printf("Enter the size of array\n");
scanf("%d", &n);
int a[n];
printf("Enter %d elements\n", n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=0; i<n; i++)
{
for(j=0; j < n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Sorted Array is:\n");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
}
Output:

Enter the size of array                                                                                                                              
5                                                                                                                                                    
Enter 5 elements                                                                                                                                     
11                                                                                                                                                   
99                                                                                                                                                   
66                                                                                                                                                   
44                                                                                                                                                   
22                                                                                                                                                   
Sorted Array is:                                                                                                                                     
11      22      44      66      99      

No comments:

Post a Comment