Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Insertion Sort in C Programming

August 25, 2013 Posted by: GPA Views: 646 0 comments

Problem

Write Insertion Sort algorithms using C language.

Solution

This article show one of the algorithms for sorting arrays. Insertion sort - it is a simple sorting algorithm. It works very simple, on each step of the algorithm, we take one of the elements of the array, then we find the position to insert and insert. Also remember that the 1-st element is already sorted. This animation helps you to understand how this algorithm works.

 

Example:

 

   

#include <stdio.h>
#include <stdlib.h>
void insertionSort(int inputarray[], int size);
int main(int argc, char *argv[])
{
         int A[8] = { 3, 5, 6, 1, 8, 7, 2, 4 };
         int size=8;//array size
         int i,j,k;//counter
         printf( "globalproganswer.com\n" );
         printf( "Array before insertion sorting:\n" );
         for ( i = 0; i < size; i++ ) {
            printf( "%d ",A[i]);
         }
         insertionSort(A,size);
         //show result after sorting
         printf("\n\nArray after insertion sorting:\n" );
         for ( i = 0; i < size; i++ ) {
            
printf( "%d ",A[i]);
         }
         printf("\n" );
         system("PAUSE");
         return 0;
}
void insertionSort(int inputarray[], int size)
{
   int i,j,k;
   int temp;
   int counterfomove=1;
   for(i=1;i<size;i++){
       for(j=i; j>0 && inputarray[j-1]>inputarray[j];j--){
            //swap
           int tmp=inputarray[j-1];
           inputarray[j-1]=inputarray[j];
           inputarray[j]=tmp;
           printf("\nArray after move #%d: ",counterfomove++);
           for (k = 0; k < size; k++){
             printf("%d ",inputarray[k]);
            }
           }
     }
}

Output

Insertion Sort in C example

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe