**Bubble 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. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Definition and the animation courtesy: Wikipedia

### Bubble Sort with C Program:

#include <stdio.h> int main() { int i, j,temp,n; int num[80]; printf("How many elements (MAX: 80): "); scanf("%d",&n); printf("Enter %d integer numbers: ",n); for(i=0;i<n;i++) scanf("%d",&num[i]); for(i=0;i<n-1;i++){ for(j=0;j<n-1-i;j++){ if(num[j]>num[j+1]){ // To sort decreasing order use num[j]<num[j+1] temp = num[j+1]; num[j+1] = num[j]; num[j] = temp; } } } printf("After sorting with Bubble Sort:\n"); for(i=0;i<n;i++) printf("%d ",num[i]); return 0; }The above program will sort the given numbers into increasing order. If you want to sort the numbers decreasing order then just change the condition from num[j]>num[j+1] to num[j]<num[j+1].

https://lh6.googleusercontent.com/-LIr-ZdDp2xI/T2WEYDacVnI/AAAAAAAACaY/W7MF5qKO2sE/s47/06.gif

ReplyDelete