C program to insert an element in the sorted array
Insertion is one of the operations performed on the arrays. So below is the program in C language to insert an element / item in the sorted array -
/* Program in C to insert the element in the sorted array */
#include<stdio.h>
void main( )
{
int a[20],n,item,i;
printf("Enter the size of the array");
scanf("%d",&n);
printf("Enter elements of the array in the sorted order");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter ITEM to be inserted : ");
scanf("%d", &item);
i = n-1;
while(item<a[i] && i>=0)
{
a[i+1] = a[i];
i--;
}
a[i+1] = item;
n++;
printf("\n\nAfter insertion array is :\n");
for(i=0; i<n; i++)
{
printf("\n%d", a[i]);
}
getch();
}
Note that the array elements to be entered in the array should be in the ascending order. As the program to made according to it. After that enter the item to be inserted and the while loop will check where the item should be inserted. It will insert the item according to the sorted ascending order.
Input -
Enter the number of elements in the array – 5
Array Elements – 5 15 25 50 52
Enter the element to be inserted – 17
Output -
Sorted array after insertion :
5 15 17 25 50 52
No comments yet