Bubble Sort in C
Written by
Bubble Sort
It is also a simple sorting algorithm. It repeatedly compares two items at a time and swapping them in ascending or descending order. The process keeps repeating itself until there are no more swaps needed.
Bubble sort has a complexity of O(n²), where n is number of items being sorted, so we should avoid using bubble sort when n is large.
# Algorithm
//bubble sort
void sort(Student st[], int n){
student temp;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (st[j].Marks < st[j + 1].Marks){
temp = st[j];
st[j] = st[j + 1];
st[j + 1] = temp;
}
}
}
}
Code:
#include<stdio.h>
int main(){
int count, temp, i, j, number[30];
printf("How many numbers are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d numbers: ",count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=count-2;i>=0;i--){
for(j=0;j<=i;j++){
if(number[j]>number[j+1]){
temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}