C program to sort an array using bubble sort algorithm

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
void bubblesort(int [],int);
int main()
{
    int *a;
    int n,i;
    printf("\nEnter the no. of elements\n");
    scanf("%d",&n);
    a=malloc(n*sizeof(int));
    printf("Enter the elements\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    bubblesort(a,n);
    printf("Sorted Array:");
    for(i=0;i<n;i++)
    {
        printf("\t%d",a[i]);
    }
    printf("\n");
    return 0;
}
void bubblesort(int a[],int n)
{
    int i,j,temp;
    for(i=0; i<n-1; i++)
    {
        for(j=0; j<n-i-1; j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
}


OUTPUT:


Enter the no. of elements
5
Enter the elements
10
50
20
30
40
Sorted Array:   10      20      30      40      50

Popular Posts