Hello friends, hope you are doing good. In this tutorial, I am going to share a c program to sort the element using bubble sort algorithm.
Bubble sort is the very simple sorting algorithm and it is a comparison-based algorithm in which each pair of adjacent elements compared and then elements are swapped if they are not in sorted in order. If you a college student or just started learning the c programming language, then this program will help you more to the better understanding of bubble sort.
1 2 3 4 5 6 7 8 9 10 11 | begin BubbleSort(list) for all elements of the list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort |
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]); } } } |
Enter no of elements :4
Enter array elements :15
20
25
30
Unsorted Data: 15 20 25 30
After pass 1 : 15 20 25 30
After pass 2 : 15 20 25 30
After pass 3 : 15 20 25 30
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: bubble sort in c program, bubble sort program in cpp, bubble sorting program in c, c program for bubble sorting, c program of bubble sort, c program on bubble sort, write a program for bubble sort in c