Monday, 13 February 2017

Insertion Sort

An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2), where n is the number of items.
Algorithm OF Insertion_Sort
Insertion_sort (A)
For (j=2 to a.length)
{
Key=a[j];
I=j-1;
While(i>=0 and a[i]>key)
{
A[i+1]=a[i];
I=i-1;
}
A[i+1]=key;
}

Program Of Insertion Sort

#include <stdio.h>

int main()
{
  int n, array[1000], c, d, t;

  printf("Enter number of elements\n");
  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++) {
    scanf("%d", &array[c]);
  }

  for (c = 1 ; c <= n - 1; c++) {
    d = c;

    while ( d > 0 && array[d] < array[d-1]) {
      t          = array[d];
      array[d]   = array[d-1];
      array[d-1] = t;

      d--;
    }
  }

  printf("Array sorted by insertion sort technic is :\n");

  for (c = 0; c <= n - 1; c++) {
    printf("%d\n", array[c]);
  }

  return 0;
}

output Of Program:-


1 comment:

  1. Thanks for share this information

    Get Secure VPS Server
    @ 1999 in India included fully managed services and Best Performance windows VPS server in India

    ReplyDelete