Algorithm of Insertion sort and a program of insertion sort in C

Insertion sort:

It is simple to sort a set of integer number or character set using insertion algorithm. Let you have unsorted array A[] of 10 elements.
A[]={23, 17, 12, 25, 33, 14, 17, 26, 21, 19}
I am showing you first six elements sorting in below.
  • 23, 17, 12, 25, 33, 14, 17, 26, 21, 19  [initially]
  • 17, 23,12, 25, 33, 14, 17, 26, 21, 19  [key= A[1] or 17 according to previous line that was sorted in this line]
  • 12, 17, 23, 25, 33, 14, 17, 26, 21, 19   [key= A[2] or 12 according to previous line]
  • 12, 17, 23, 2533, 14, 17, 26, 21, 19   [key= A[3] or 25 according to previous line, but here after first comparison of 12 with previous element we see no need to sort ]
  • 12, 17, 23, 25, 33, 14, 17, 26, 21, 19   [key=A[4] or 33 according to previous line, but here after first comparison of  with previous element we see no need to sort ]
  • 12, 14, 17, 23, 25, 33, 17, 26, 21, 19 and that’s way all elements are sorted.
You have seen that every time key is placed in proper location in the array. We have seen that before all elements of a key have already been sorted
so we just need to find the place for key according to demand. If we want to arrange an array elements in increasing mode then we only forward previous elements of key if it is larger than key. When we see a element is not larger than key, we place the key element in front of this element. Have look on the algorithm which is known as insertion algorithm.

INSERTION

  1.       Take a input of an array A consisted N elements.
  2.      For i=1 to N-1                                     // since we allowed here first location of array is 0
  3.            Key=A[i]
  4.            J=i-1                                                // initialize the previous location of key element
  5.           While j >= 0  and  A[j] > key
  6.                      A[j+1] = A[j]                         // forwarding A[j] element into its front location
  7.                      J= j-1                                     //going to another previous element of key element
  8.            // End of while loop
  9.             A[j+1] = key                                   // placing key element in a niche place until moving into next key element




#include <stdio.h>
#define MAX 100
int insertion_sort(int *A, int n);

int main() {
int  A[MAX], i, N;
printf ("How many array elements: ");
scanf ("%d", &N);
printf ("\nEnter elements: \n");
for (i=0;i<N;i++){
scanf ("%d", &A[i]);
}
insertion_sort (A,N);
printf ("\nAfter sorting the array is:\n");
for (i=0;i<N;i++)
printf ("%d\t", A[i]);

return 0;
}

int insertion_sort (int *A, int n){

int  i, j, key;
for (i=1;i<n; i++){
key = A[i];
j = i-1;
while (j>=0  &&  A[j]>key){
A [j+1] = A[j];
j = j-1;
}
A[j+1] = key;
}
return *A;
}

 

No comments:

Post a Comment