Bubble Sort
What is Sorting?
Sorting is a technique of rearranging the elements in any particular order. It might be in either ascending or descending sequence.
Describe Bubble sort algorithm with example
Bubble sort is an algorithm for sorting a list of elements. It compares nearby components and swaps them if they are not in the correct sequence. This step is continued until the list is sorted.
Example:
Input list: 4, 2, 8, 6, 1
Step 1: Compare 4 and 2, since 4 is greater than 2, swap them. List is now 2, 4, 8, 6, 1
Step 2: Compare 4 and 8, since 4 is less than 8, no swap needed.
Step 3: Compare 8 and 6, since 8 is greater than 6, swap them. List is now 2, 4, 6, 8, 1
Step 4: Compare 8 and 1, since 8 is greater than 1, swap them. List is now 2, 4, 6, 1, 8
Step 5: List is sorted, no more swaps needed.
Sorted list: 1, 2, 4, 6, 8
Bubble Sort in C Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //Bubble Sort in C Program #include<conio.h> #include<stdio.h> int main() { int i,j,b,n,a[10]; clrscr(); printf("\nEnter The Limit : "); scanf("%d",&n); printf("\nEnter array Elements : n"); for(i=1;i<=n;i++) { scanf("%d",&a[i]); } for(i=1;i<n-1;i++) { for(j=1;j<n-i;j++) { if(a[j]>a[j+1]) { b=a[j]; a[j]=a[j+1]; a[j+1]=b; } } } printf("\nThe Sorted Elements : \n"); for(i=1;i<=n;i++) printf(" %d ",a[i]); getch(); return 0; } |
Input
Enter The Limit :6
Enter array Elements :
2
5
3
7
6
1
Output
The Sorted Elements :
1
2
3
5
6
7
Read Also