Home » Code Snippets » C/C++ Data Structure programs

Insertion Sort Data Structure Example in C - Program to arrange elements in Ascending, Descending Order



Insertion Sort is a simple sorting method for small data list, in this sorting technique one by one element shifted. Insertion Sort has very simple implementation and efficient for small data sets.

C program for Data Structure Insertion Sort Example - In this program we will read N number of elements in a One Dimensional Array and arrange all elements in Ascending and Descending Order using Data Structure Insertion Sort technique.

Data Structure - Insertion Sort Example using C program

/*Insertion Sort - C program to sort an Array 
in Ascending and Descending Order.*/
 
#include <stdio.h>
 
#define MAX 100
 
int main()
{
    int arr[MAX],limit;
    int i,j,temp;
     
    printf("Enter total number of elements: ");
    scanf("%d",&limit);
     
    /*Read array*/
    printf("Enter array elements: \n");
    for(i=0; i<limit; i++)
    {
        printf("Enter element %3d: ",i+1);
        scanf("%d",&arr[i]);
    }
     
    /*sort elements in Ascending Order*/
    for(i=1; i<(limit); i++)
    {
        j=i;
        while(j>0 && arr[j]<arr[j-1])
        {
            temp=arr[j];
            arr[j]=arr[j-1];
            arr[j-1]=temp;
             
            j--;
        }
    }
 
    printf("Array elements in Ascending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
     
    printf("\n");
         
    /*sort elements in Descending Order*/
    for(i=1; i<(limit); i++)
    {
        j=i;
        while(j>0 && arr[j]>arr[j-1])
        {
            temp=arr[j];
            arr[j]=arr[j-1];
            arr[j-1]=temp;
             
            j--;
        }
    }
 
    printf("Array elements in Descending Order:\n");
    for(i=0; i<limit; i++)
        printf("%d ",arr[i]);
         
    printf("\n");
     
    return 0;
}

Output

    Enter total number of elements: 10
    Enter array elements: 
    Enter element 1: 40 
    Enter element 2: 10 
    Enter element 3: 100
    Enter element 4: 20 
    Enter element 5: 90 
    Enter element 6: 60 
    Enter element 7: 80 
    Enter element 8: 70 
    Enter element 9: 30 
    Enter element10: 50 
    Array elements in Ascending Order:
    10 20 30 40 50 60 70 80 90 100
    Array elements in Descending Order:
    100 90 80 70 60 50 40 30 20 10





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.