Insertion sort
using ‘c’
Inclusion sort is a basic arranging calculation that works by building an arranged sublist each component in turn. It keeps a to some extent arranged cluster and emphasizes through the unsorted part, taking every component and embedding it into the right situation in the arranged sublist.
Here is the bit by bit course of the addition sort calculation:
1. Begin with the subsequent component (file 1) and consider it as the "key".
2. Contrast the key and the component before it (past component) and assuming the key is more modest, push the past component one situation forward.
3. Rehash stage 2 for all components before the key while the key is more modest than them.
4. Embed the key into the right position tracked down in the past advances.
5. Move to the following component and rehash stages 2-4 until all components are arranged.
Program:-
void insert(int a[], int n)
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j])
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int k;
printf("Enter no of elements to sort");
scanf("%d",&k);
int a[k];
for(int i=0;i<k;i++)
scanf("%d",&a[i]);
//int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, k);
insert(a, k);
printf("\nAfter sorting array elements are - \n");
printArr(a, k);
return 0;
}
Output
0 Comments