In this post, let’s see how to implement bubble sort in C.
Bubble sort, also known as sinking sort,compares adjacent elements and swap them if they are not in correct order.
Here is a simple illustration of bubble sort.
Above GIF is generated from algorithms app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<stdio.h> int main() { int i,j,temp; int myArray[] = {67,23,45,74,12,34}; int n = sizeof(myArray)/sizeof(int); printf("\nArray before sorting: "); for(i=0;i<n printf for i="0;" n j="0;" if>myArray[j+1]) { temp=myArray[j]; myArray[j]=myArray[j+1]; myArray[j+1]=temp; } } } printf("\nArray after sorting: "); for(i=0;i<n printf return></n></n></stdio.h> |
Output:
Array before sorting: 67 23 45 74 12 34
Array after sorting: 12 23 34 45 67 74
Array after sorting: 12 23 34 45 67 74
Both worst case and average case complexity is O (n^2) for bubble sort.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.