Insert an element at appropriate position in a sorted array
C program to insert an element at appropriate position in a sorted array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
int find_pos(int a[MAX], int n, int num)
{
int i, pos, flag;
flag = 0;
for(i=0;i<n;i++)
{
if(a[i]>num)
{
return (i+1);
flag = 1;
break;
}
}
if(flag==0)
{
return(n+1);
}
}
void insert(int a[MAX], int n, int num, int pos)
{
int i;
for(i=n-1;i>=pos-1;i--)
{
a[i+1] = a[i];
}
a[pos-1] = num;
}
void main()
{
int arr[MAX];
int i, n, num, pos;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array in sorted order(ascending)\n");
read_array(arr, n);
printf("Enter the element to be inserted\t:");
scanf("%d",&num);
pos = find_pos(arr, n, num);
if(pos>n+1)
printf("\nElement cannot be entered at %d position",pos);
else
{
insert(arr, n, num, pos);
printf("\nModified array is\n");
print_array(arr, n+1);
}
getch();
}
Output
Enter the number of elements in the array :6
Enter the elements of the array in sorted order(ascending)
Element 1 :3
Element 2 :5
Element 3 :7
Element 4 :9
Element 5 :12
Element 6 :34
Enter the element to be inserted :8
Modified array is
Element 1 :3
Element 2 :5
Element 3 :7
Element 4 :8
Element 5 :9
Element 6 :12
Element 7 :34