In insertion sort newly inserted element are placed to their sorted location.
Suppose , if we want to insert 5 elements into required space or place and ( 0 , 1 , 2 , 3 , 4 ) are their index or location where the element are stored. Now we first check the space whether it is require for inserting element or not.If space is required.
ALGORITHM OF INSERTION SORT:
Algorithm Insertionsort (A , N)
A is an array with N elements.
STEP 1 : FOR I = 0 TO N - 1 DO
STEP 2 : K = I - 1
STEP 3 : READ X
STEP 4 : WHILE K > = 0 AND A [K] > X
STEP 5 : A[ K + 1] = A[K]
STEP 6 : K= K + 1
STEP 7 : END WHILE
STEP 8 : A[ K + 1] = X
STEP 9 : NEXT I
STEP 10: END
PROCEDURE OF INSERTION SORT:
void Insertionsort sort ( int a[50] , int n )
{
int i , k , x ;
for( i=0 ; i<=n-1 ; i++ )
{
k = i - 1;
printf ( " Enter x: " ) ;
scanf ( " % d " , & x ) ;
while ( k >=0 && a[k] > x)
{
a [ k + 1 ] = a[k] ;
k - - ;
}
a [ k + 1] = x ;
}
}
Note , here (k) point to right most element.
LOGIC DIAGRAM
No comments:
Post a Comment