Bubble sort
Its an easy sorting algorithm to learn and implement.Bubble sort algorithm is good for Small data set . It is not good for larger data sets.
code...
#include<stdio.h>
int main(){
int a[5]={2,1,0,4,7},i=0,j=0,n=5,temp=0;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
// Comparing the elements
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
// Print the Sorted Array
for(i=0;i<n;i++){
printf("%d\t",a[i] );
}
return 0;
}
I have taken an array and we are comparing last previous element with the next element and if previous element is larger than current element than Swap them.
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
This part is main part which is swapping the elements with current and previous elements.
Its an easy sorting algorithm to learn and implement.Bubble sort algorithm is good for Small data set . It is not good for larger data sets.
code...
#include<stdio.h>
int main(){
int a[5]={2,1,0,4,7},i=0,j=0,n=5,temp=0;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
// Comparing the elements
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
// Print the Sorted Array
for(i=0;i<n;i++){
printf("%d\t",a[i] );
}
return 0;
}
I have taken an array and we are comparing last previous element with the next element and if previous element is larger than current element than Swap them.
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
This part is main part which is swapping the elements with current and previous elements.
Comments
Post a Comment