Thursday, June 9, 2016

Insertion Sort in C

This is the code in C language for Insertion Sort. If you run the program, the program asks for the size of the array followed by all the elements of the array. It prints the sorted elements in increasing order.
      
        #include <stdio.h>
        #include <stdlib.h>

        void insertionsort(long long int * A, long long int N)
        {
            long long int x, y, key;
            for(x=1; x<N; x++)
            {
                key = A[x];
                for(y=x-1; y>=0 && key>A[y]; y--)
                {
                    A[y+1] = A[y];
                }
                y++;
                A[y] = key;
            }
        }

        int main()
        {
            long long int N, x;
            scanf("%lld", &N);
            long long int * A = malloc(N*sizeof(long long int));
            for(x=0; x<N; x++)
            {
                scanf("%lld", &A[x]);
            }

            insertionsort(A, N);

            for(x=0; x<N; x++)
            {
                printf("%lld ", A[x]);
            }
            return 0;
        }