Headlines
Loading...
Data structure Program -Simple Insertion Sort

Data structure Program -Simple Insertion Sort

/* Simple Insertion Sort */

#include
#include

#define MAXNOS 100 /* Macro definition for maximum numbers to be input */

void insertion(int *, int); /* sorting function prototype declaration */

void main(void)
{
int a[MAXNOS]; /* array to hold the input numbers */
int m; /* stores the total count of input numbers */
int i; /* for loop variable */
input : /* label name for transfer of control through goto */
clrscr();
printf("Simple Insertion Sort\n");
printf("------ --------- ----\n\n");
printf("Enter how many numbers will be input for sorting - ");
flushall();
scanf("%d", &m);
if (m < 1 || m > MAXNOS) /* check for valid input */
{
printf("Error - input value is out of range...");
getch();
goto input;
}
printf("Enter the numbers one by one -\n");
for (i=0; i {
printf("%2d - ", (i+1));
flushall();
scanf("%d", &a[i]);
}
insertion(a, m); /* function is invoked for sorting the numbers */
printf("\n\nSorted numbers are - \n");
for (i=0; i printf("%d\t", a[i]); /* sorted numbers are displayed on the screen */
getch();
}

void insertion(int *x, int n) /* function definition begins here */
{
int i, j, hold;
for (i=1; i {
hold = x[i]; /* stores value of first number of unsorted set */
/* to be considered for insertion in sorted set */
for (j=(i-1); j>=0 && hold < x[j]; j--)
/* loop for insertion in the correct place */
{
x[j+1] = x[j]; /* shift the larger number down to the right */
} /* end of for with loop variable = j */
x[j+1] = hold; /* insert the number in the right place */
} /* end of for statement with loop varable = i */
} /* end of insertion function */



*** PLEASE checkout the Best deals from for top sites like Amazon, Flipkart etc ***