In this post, we will learn how to bubble sort an array using the C Programming language.
Bubble sort is a simple sorting algorithm inĀ which pairs of adjacent elements are compared, and the elements are swapped if they are not in order.
We will be sorting the elements of the list in ascending order using bubble sort.
So, without further ado, let’s begin this tutorial.
C Program For Bubble Sorting
// C Program For Bubble Sorting #include <stdio.h> int main(){ int i, j, temp, count, num[10]; //Asking for input printf("Enter total no. of elements: \n"); scanf("%d", &count); printf("Enter %d elements:", count); for (i = 0; i < count; i++) scanf("%d", &num[i]); //Sorting elements for (i = count - 2; i >= 0; i--) for (j = 0; j <= i; j++){ if (num[j] > num[j + 1]){ temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; } } //Displaying the sorted elements printf("Sorted Elements: "); for (i = 0; i < count; i++){ printf("%d ", num[i]); } return 0; }
Output
Enter total no. of elements:
5
Enter 5 elements:17
12
20
18
7
Sorted Elements: 7 12 17 18 20
How Does This Program Work ?
int i, j, temp, count, num[10];
In this program, we have declared some int data type variables which will store the value of the elements of the list.
//Asking for input printf("Enter total no. of elements: \n"); scanf("%d", &count); printf("Enter %d elements:", count); for (i = 0; i < count; i++) scanf("%d", &num[i]);
Then, the user is asked to enter the total no. of elements and value of each of the elements.
//Sorting elements for (i = count - 2; i >= 0; i--) for (j = 0; j <= i; j++){ if (num[j] > num[j + 1]){ temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; } }
Now, we have used simple logic to sort the elements.
//Displaying the sorted elements printf("Sorted Elements: "); for (i = 0; i < count; i++){ printf("%d ", num[i]); }
Finally, the sorted elements are printed in ascending order using printf() function.
Conclusion
I hope after going through this post, you understand how to bubble sort using C Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.
Also Read: