Program to enter n set of elements inside 1-D array and arrange these elements using bubble sort & selection sort.

Selection Sort:

#include<stdio.h>
main()
{
    int i,j,n,a[50],temp;
    printf("Enter the size of the array \n");
    scanf("%d",&n);
    printf("Enter elements\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",(a+i));
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j<i;j++)
        {
            if(*(a+i)< *(a+j))
            {
                temp = *(a+i);
                *(a+i)=*(a+j);
                *(a+j)=temp;
            }
        }
    }
    printf("\nThe sorted array is ");
    for(i=0;i<n;i++)
    printf("%d",*(a+i));
}

 

Bubble Sort:

#include<stdio.h>
main()
{
    int a[100],i,j,n,temp;
    printf("Enter size of array");
    scanf("%d",&n);
    printf("Enter elements\n");
    for(i=0;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("\n");
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=(n-i);j++)
        {
            if(*(a+j)>*(a+j+1))
            {
                temp=*(a+j);
                *(a+j)=*(a+j+1);
                *(a+j+1)=temp;

            }
        }
    }

    printf("The sorted array is \n");
    for(i=1;i<=n;i++)
    {
        printf("%d\n",*(a+i));
    }
}

 

Output [Selection Sort]:

selection

Output [Bubble Sort]:

bubble

Leave a Reply

Your email address will not be published.