Write a procedure (function) in C that inserts an element in a sorted array. The
ID: 3793694 • Letter: W
Question
Write a procedure (function) in C that inserts an element in a sorted array. The prototype of the function should be something similar to the following: insertelm(int elm, int arr[], int size); where elm is the element to be inserted, arr [] is the array to insert the element to. size is the initial size of the array. Illustration: Suppose an array named arr contains the following sequence of integers: Calling function insertelm (9, arr, 5); would insert the new member 9 in the right position as shown below:Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertelm(int, int [], int);
void main()
{
int arr[500], size, elm, i;
printf("Enter the size of the array");
scanf("%d", &size);
printf("Enter elements of the array in the sorted order");
for (i = 0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf(" Enter ITEM to be inserted : ");
scanf("%d", &elm);
insertelm(elm, arr, size);
getch();
}
void insertelm(int elm, int arr[], int size)
{
int i;
i = size - 1;
while (elm<arr[i] && i >= 0)
{
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = elm;
size++;
printf(" After insertion array is : ");
for (i = 0; i<size; i++)
{
printf(" %d", arr[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.