Wednesday 20 August 2014

Filled Under:

C program to sort elements using Bubble sort

Share

C program to sort elements using Bubble sort

 There is a C program to sort elements using Bubble sort is given below,bubble sort, sometimes referred to as sinking sort, 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.C programming code  for bubble sort to sort numbers or arrange them in ascending order. You can easily modify it to print numbers in descending order.
In the bubble sort, as elements are sorted they gradually “bubble” (or rise) to their proper location in the array, like bubbles rising in a glass of soda.  The bubble sort repeatedly compares adjacent elements of an array.  The first and second elements are compared and swapped if out of order.  Then the second and third elements are compared and swapped if out of order.  This sorting process continues until the last two elements of the array are compared and swapped if out of order. 

C program to sort elements using Bubble sort

#include <stdio.h>
void bubble_sort();
int a[50], n;
main()
{
 int i;
 printf("nEnter size of an array: ");
 scanf("%d", &n);
 printf("nEnter elements of an array:n");
 for(i=0; i<n; i++)
 scanf("%d", &a[i]);
 bubble_sort();
 printf("nnAfter sorting:n");
 for(i=0; i<n; i++)
 printf("n%d", a[i]);
 getch();
}

void bubble_sort()
{

 int j, k, temp;
 for(j=0; j<n; j++)
 for(k=0; k<(n-1)-j; k++)
 if(a[k] > a[k+1])
 {
   temp = a[k];
   a[k] = a[k+1];
   a[k+1] = temp;
 }
}

Output
Enter size of an array:10
Enter elements of an array:23 43 56 34 12 34 55 65 76 21
After sorting:12 21 23 34 34 43 55 56 65 76