Monday 13 November 2017

C Program to Implement Insertion Sort


Code:

#include   stdio.h
#define MAX 7

void insertion_sort(int *);

void main()
{
    int a[MAX], i;

    printf("enter elements to be sorted:");
    for (i = 0;i < MAX;i++)
    {
        scanf("%d", &a[i]);
    }
    insertion_sort(a);
    printf("sorted elements:\n");
    for (i = 0;i < MAX; i++)
    {
        printf(" %d", a[i]);
    }
}

/* sorts the input */
void insertion_sort(int * x)
{
    int temp, i, j;

    for (i = 1;i < MAX;i++)
    {
        temp = x[i];
        j = i - 1;
        while (temp < x[j] && j >= 0)
        {
            x[j + 1] = x[j];
            j = j - 1;
        }
        x[j + 1] = temp;
    }
}


Output:


enter elements to be sorted:8 2 4 9 3 6 1
sorted elements:
 1 2 3 4 6 8 9

enter elements to be sorted:1 2 3 4 5 6 7
sorted elements:
 1 2 3 4 5 6 7

enter elements to be sorted:7 6 5 4 3 2 1
sorted elements:
 1 2 3 4 5 6 7



More C Programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...