Saturday 19 March 2016

Insertion Sort


Write a C program to perform insertion sort on an array of n elements.

Input Format: 
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next n integers correspond to the elements in the array.

Output Format: 
Refer sample output for formatting specs.

Sample Input and Output: 
[All text in bold corresponds to input and the rest corresponds to output]
Enter the number of elements in the array
5
Enter element 1
4
Enter element 2
2
Enter element 3
7
Enter element 4
3
Enter element 5
1
Insertion sort.
array before sorting:
4 2 7 3 1
After Iteration 1
2 4 7 3 1
After Iteration 2
2 4 7 3 1
After Iteration 3
2 3 4 7 1
After Iteration 4
1 2 3 4 7
array after sorting: 1 2 3 4 7

Code:

  #include<stdio.h>
void insertionsort(int *, int);
int main(void)
{
  int n, a[20],i;
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  for (i=0;i<n;++i)
  {
    printf("Enter element %d\n",i+1);
    scanf("%d",&a[i]);
  }
  printf("Insertion sort.\narray before sorting:\n");
  for (i=0;i<n;i++)
    printf("%d ",a[i]);
  insertionsort(a,n);
  return 0; 
}

void insertionsort(int *a, int size)
{
  int value, hole,i,j;
  for(i=1;i<size;++i)
  {
    value=a[i];
    hole=i-1;
    while(hole>=0 && a[hole]>value)
    {
      a[hole+1]=a[hole];
      hole=hole-1;
    }
    a[hole+1]=value;
    printf("\nAfter Iteration %d\n",i);
    for(j=0;j<size;j++)
      printf("%d ",a[j]);
}
  printf("\narray after sorting:\n");
  for(j=0;j<size;j++)
    printf("%d ",a[j]);
}

3 comments:

  1. int must have the value of 'n' inside the function.
    i.e.all 'size' must be changed as 'n' for a successful execution!

    ReplyDelete
  2. Very informative article.Thank you author for posting this kind of article .

    http://www.wikitechy.com/view-article/insertion-sorting-

    program-in-cpp-with-example-and-explanation



    Both are really good,
    Cheers,
    Venkat

    ReplyDelete
  3. The Karnataka Examinations Authority has already announced to download the Admit Card KCET on the official site.

    ReplyDelete