Insertion sort in C program

Thursday, December 4th, 2008

Here is the program to sort the given integer in ascending order using insertion sort method. Please find the pictorial tutor of the insertion sorting.

Logic : Here, sorting takes place by inserting a particular element at the appropriate position, that’s why the name-  insertion sorting. In the First iteration, second element A[1] is compared with the first element A[0]. In the second iteration third element is compared with first and second element. In general, in every iteration an element is compared with all the elements before it. While comparing if it is found that the element can be inserted at a suitable position, then space is created for it by shifting the other elements one position up and inserts the desired element at the suitable position. This procedure is repeated for all the elements in the list.

If we complement the if condition in this program, it will give out the sorted array in descending order. Sorting can also be done in other methods, like selection sorting and bubble sorting, which follows in the next pages.

Insertion Sort Demo

Insertion Sort Demo

C program for Insertion Sort:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<stdio.h>
void main()
{
	int A[20], N, Temp, i, j;
	clrscr();
	printf("\n\n\t ENTER THE NUMBER OF TERMS...: ");
	scanf("%d", &N);
	printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:");
	for(i=0; i<N; i++)
	{
		gotoxy(25,11+i);
		scanf("\n\t\t%d", &A[i]);
	}
	for(i=1; i<N; i++)
	{
		Temp = A[i];
		j = i-1;
		while(Temp<A[j] && j>=0)
		{
			A[j+1] = A[j];
			j = j-1;
		}
		A[j+1] = Temp;
	}
	printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");
	for(i=0; i<N; i++)
		printf("\n\t\t\t%d", A[i]);
	getch();
}

Download exe and source code here.

Author Name :
Ranjith

Total : 189 Comments


189 Responses to “Insertion sort in C program”

  1. jamila says:

    yupeeeeeeeeeeeee,i got selection sort,thanks to u….

  2. jamila says:

    nice!but u people has to keep code in easy manner plz…

  3. jamila says:

    i want to learn insertion sort….

  4. Ranjit The Bandit says:

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

    /* Configuration */

    static struct conv {
            int ch;
            const char *replace;
    } tab[] = {
            { ’<’,        "&lt;" },
            { ’>’,        "&gt;" },
            { ’ ’,        "&nbsp;" },
            { ’&’,        "&amp;" },
            { ’\"’,        "&quot;" },
            { 0,        0 }
    };

    static const char *tabstr = "&nbsp;";
    static int tabspaces = 8;
    static int usebreaks = 0;

    /* End of configuration */

    static int eol(int c, FILE *stream)
    {
            if (c == ’\n’)
                    return 1;
            if (c == ’\r’) {
                    if ((c = getc(stream)) != ’\n’)
                            ungetc(c, stream);
                    return 1;
            }
            return 0;
    }

    static const char *getstr(int c)
    {
            struct conv *t = tab;

            while (t->replace) {
                    if (c == t->ch)
                            return t->replace;
                    t++;
            }
            return 0;
    }

    static void tabify(FILE *dest, int n, const char *s)
    {
            while (n–)
                    fputs(s, dest);
    }

    static int htmlify(FILE *dest, FILE *src)
    {
            int c;

            while ((c = getc(src)) != EOF) {
                    const char *s;

                    if (usebreaks && eol(c, src)) {
                            fputs("<br />", dest);
                            continue;
                    }
                    if (c == ’\t’) {
                            tabify(dest, tabspaces, tabstr);
                            continue;
                    }
                    s = getstr(c);
                    if (s)
                            fputs(s, dest);
                    else
                            putc(c, dest);
            }
            return ferror(dest);
    }

    static const char *progname = "htmlify";

    int main(int argc, char *argv[])
    {
            FILE *stream;
            int retval;

            if (argv[0] && argv[0][0] != ”)
                    progname = argv[0];
            if (argc != 2) {
                    fprintf(stderr, "Usage: %s c-source-file\n", progname);
                    return EXIT_FAILURE;
            }
            stream = fopen(argv[1], "r");
            if (!stream) {
                    fprintf(stderr, "%s: %s: %s\n", progname, argv[1],
                            strerror(errno));
                    return EXIT_FAILURE;
            }
            retval = htmlify(stdout, stream) ? EXIT_FAILURE : 0;
            fclose(stream);
            return retval;
    }

  5. Maple Zhou says:

    /*
    * Program: InsertionSort.c
    * Written by: iMaple
    * Date:5, 25, 2012
    * Comliler: vs2010
    */

    #include

    //Function Declaration
    void InsertionSort(int a[], int Length);

    int main(void)
    {
    int array[] = {21, 10, 15, 88, 95, 05};

    InsertionSort(array, 6);
    return 0;
    }//main

    void InsertionSort(int a[], int Length)
    {
    int counter;
    int lookuper;
    int temp;

    for (counter = 1; counter 0&&a[lookuper - 1]>temp; lookuper–)
    a[lookuper] = a[lookuper - 1];
    a[lookuper] = temp;
    }//for
    printf(“\n\t The sorted list is ….”);
    for (counter = 0; counter < 6; counter++)
    printf("\n\n%2d\n", a[counter]);
    return;
    }//InsertionSort

  6. NAUMAN says:

    its help alot! Thanxxx nd Keep posting…!!

  7. NAUMAN says:

    nice explanation…!!
    thanxx

  8. mahesh says:

    samjle nahi……….. simple language madhe sangat ja….. jay maharashtra

  9. rishabh sharma says:

    void main()
    {
    int a[20],temp,j,i,n;
    clrscr();
    printf(“enter no. of elements\n”);
    scanf(“%d”,&n);
    printf(“enter elements\n”);
    for(i=1;i<=n;i++)
    scanf("%d",&a[i]);
    for(i=1;i<=n;i++)
    {
    for(j=1;ja[j+1])
    {
    temp=a[j];
    a[j]=a[j+1];
    a[j+1]=temp;
    }
    }
    }
    for(i=1;i<=n;i++)
    printf("\n%d",a[i]);
    getch();
    }

  10. rishabh sharma says:

    simplest

  11. shital says:

    very nice demo.

  12. Hrvoje says:

    Hi
    cod you hellp me with some tasks? ?

  13. Balaji says:

    What is gotoxy….? Can u hlep me plz…

  14. arunsekar says:

    very nice demo

  15. soumik says:

    #include
    #include
    void selection(int at J,int n)
    {
    int i,j,min,loc;
    for(i=0;i<n-1;i++)
    {
    min=a[i];
    loc=i+1;J<n.J++)
    {
    if(a[j]<min)
    {min=a[J];
    loc=J;
    }
    }
    a[loc]=a[i];
    a[i]=min
    }
    }

  16. romel says:

    it helps me alot…tnx

  17. Pranav says:

    void swap(int *src, int *dest)
    {
    int temp;
    temp = *src;
    *src = *dest;
    *dest = temp;
    }

    main ()
    {
    int a[] = {4,8,7,3,2,9,0,1,6,5};
    unsigned int n = sizeof(a)/sizeof(a[0]);
    int i=0, j=0;

    for(i=1; i=0; j–) {
    if(a[j] > a[j+1]) {
    swap(&a[j+1], &a[j]);
    }
    }
    }

    for(i=0; i<n; i++)
    printf("Sorted list : %d ", a[i]);

    return 0;
    }

  18. pooja says:

    thankx sir ye program to hmara run hi nahi ho raha tha but now i done it

  19. shadabi mansoor alam says:

    Its very helpful for me,now every confusion has been finished…………..so thank you so so …………..much.

  20. shadabi mansoor alam says:

    Its very helpful for me,now every confusion has been cleared…………..so thank you so so …………..much.

  21. kavish says:

    just WOWWW…

  22. Vipul says:

    Your diagram and code doestnt match!
    Program is good, but not diagram.

  23. sumit gupta says:

    #include
    void main()
    {
    int A[20], N, Temp, i, j;
    clrscr();
    printf(“\n\n\t ENTER THE NUMBER OF TERMS…: “);
    scanf(“%d”, &N);
    printf(“\n\t ENTER THE ELEMENTS OF THE ARRAY…:”);
    for(i=0; i<N; i++)
    {
    gotoxy(25,11+i);
    scanf("\n\t\t%d", &A[i]);
    }
    for(i=1; i<N; i++)
    {
    Temp = A[i];
    j = i-1;
    while(Temp=0)
    {
    A[j+1] = A[j];
    j = j-1;
    }
    A[j+1] = Temp;
    }
    printf(“\n\tTHE ASCENDING ORDER LIST IS…:\n”);
    for(i=0; i<N; i++)
    printf("\n\t\t\t%d", A[i]);
    getch();
    }

  24. sathish says:

    thank u . . .Its is very useful . . .Keep posting more codes . .

  25. sathish says:

    i want print like this
    .1
    A B
    2 3 4
    C D E F . . . .like this any one help me write the coding for that

  26. CJ says:

    Sir. can you do a dutch flag problem using a insertion sort?

  27. bhavika says:

    kya hai.. kuch output nai ara hai

  28. sakshi says:

    simulation of sorting (all sorting)

  29. sakshi says:

    simulation of sorting(all sorting) progam in c language

  30. potpot says:

    i need a unique & short program using insertion sort ?? can you help me ?

  31. chetna goyal says:

    hii..i want to know the meaning of why we use j=j-1 after assigning temp to a[i] in insertion sort..please explain it as soon as possible my mail id is gchetna30@gmail.com.

  32. karamjeet virk says:

    main()
    #define size 10
    {
    int arr[size],i,j,item;
    printf(“\n enter the element in array”);
    for(i=0;i<size;i++)
    scanf("%d",&arr[i]);
    for(j=0;j<size;j++)
    { item=arr[i];
    for(i=j-1;item=0;i–)
    { arr[i+1]=arr[i];
    arr[i]=item;
    }}

  33. keval says:

    thnxx.
    i understood insertion stood.

  34. AOT says:

    For balchhal programs contact AOT guys….West bengal…chodao bara

  35. merusha says:

    Rohon dar gude batha…tai boli dudu khao..

  36. keerthika says:

    sir,i want to know what is use of gotoxy()?

  37. pls multy way tree sample program for ds insertion deletion plz............ says:

    multy way tree

  38. ATCHUTA RAO says:

    #include
    #include
    void main()
    {
    int a[20],k,n,i=0,j=0,t=0;

    clrscr();
    printf(“no of of elemts”);
    scanf(“%d”,&n);
    printf(“enter %d values”,n);
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);

    for(i=1;i=1;j–)
    {

    printf(“i=%d j=%d %d %d”,i,j,a[j],a[j-1]);
    if(a[j]>a[j-1])
    break;
    else
    {
    t=a[j];
    a[j]=a[j-1];
    a[j-1]=t;
    }

    } printf(“\n”);
    } printf(“\n”);

    for(i=0;i<n;i++)
    printf(" %d ",a[i]);
    getch();
    }

    THE ABOVE CODE REPRESENTS WHICH SORTING TECHNIQUE????

    DOES IT REPRESENT INSERTION SORT????

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup

Email: