C Program to Implement Bubble Sort in C Programming
Bubble Sort in C : All Passes
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 33 34 35 36 37 38 39 40 41 42 | #include<stdio.h> #include<conio.h> void bubble_sort(int[], int); void main() { int arr[30], num, i; printf("\nEnter no of elements :"); scanf("%d", &num); printf("\nEnter array elements :"); for (i = 0; i < num; i++) scanf("%d", &arr[i]); bubble_sort(arr, num); getch(); } void bubble_sort(int iarr[], int num) { int i, j, k, temp; printf("\nUnsorted Data:"); for (k = 0; k < num; k++) { printf("%5d", iarr[k]); } for (i = 1; i < num; i++) { for (j = 0; j < num - 1; j++) { if (iarr[j] > iarr[j + 1]) { temp = iarr[j]; iarr[j] = iarr[j + 1]; iarr[j + 1] = temp; } } printf("\nAfter pass %d : ", i); for (k = 0; k < num; k++) { printf("%5d", iarr[k]); } } } |
What Happens After Each Iteration ?
- There are ‘N’ number of Unsorted Elements
- Total Number of Iterations = N-1
- At the End of First Iteration : Largest Element Will get its Exact Final Position
- At the End of 2nd Iteration : 2nd Largest Element Will get its Exact Final Position
- .
- .
- .
- .
- At the End of (N-1)th Iteration : (N-1)th Largest Element Will get its Exact Final Position
Output :
1 2 3 4 5 6 7 8 | Enter no of elements :5 Enter array elements :10 4 55 21 6 Unsorted Data: 10 4 55 21 6 After pass 1 : 4 10 21 6 55 After pass 2 : 4 10 6 21 55 After pass 3 : 4 6 10 21 55 After pass 4 : 4 6 10 21 55 |