C Program to Implemention Bubble Sort using array

How to write a C Program to Implement Bubble Sort in C Program Language ?

/* Bubble sort : In bubble sort, we compare first two elements of array; then move one block ahead and compare the elements again until the last element; at the end we have the highest numeric value to the end; This process is iterated n times ( n -> no. of elements in array) and finally the sorted output is attained... We have used (6-i) in the "second for loop" so as to improve the performance as the last element(n) is not required to be computed as the iteration proceeds n times....*/


// bubble sort

#include <stdio.h>
#include <stdlib.h>

int main()
{
int arr[6],i,j,temp,n;

printf("Enter the number of elements in the array\n");
scanf("%d",&n);

for(i=0; i<n;i++)
{

printf("Enter the number of elements in the array\n");
scanf("%d",&arr[i]);
}


for(i=0; i<n; i++)
{

for(j=1; j<=n-i; j++)
{

if(arr[j-1] > arr[j])
{
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}

else if(arr[j-1] < arr[j])
{
break;
}
}

}

for(i=0; i<n; i++)
{
printf("The sorted order is: \n");
printf("%d\n",arr[i]);
}
}



Learn More :