/*Code for inserting in a sorted array*/
#include<stdio.h>
int insertSorted(int *a,int *size,int item);
int main()
{
int n,i;
int a[]={2,4,6,8,10};
printf("Original sorted array is:\n");
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter element to insert:\n");
scanf("%d",&n);
int size=5;
insertSorted(a,&size,n);
printf("\nAfter Inserted sorted array is:\n");
for(i=0;i<=5;i++)
{
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
int insertSorted(int *a,int *size,int item)
{
int i,j;//i is position
if(*size<0) {printf("Enter a positive array size.\n"); return;}
/*Determine the location to insert.*/
if(item<a[0])
{
i=0;
}
else
{
for(i=1;i<*size;i++)
{
if(( item<=a[i]) && (item>=a[i-1]))
{
break;//come out of the loop when right position
}
}
}
/*Shift the elemets after the position to insrt to right*/
for(j=*size;j>=i;j--)
a[j]=a[j-1];
/*Insert the lement at rigt postion*/
a[i]=item;
(*size)++;
}
/*
Original sorted array is:
2 4 6 8 10
Enter element to insert:
11
After Inserted sorted array is:
2 4 6 8 10 11
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
1
After Inserted sorted array is:
1 2 4 6 8 10
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
33
After Inserted sorted array is:
2 4 6 8 10 33
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
3
After Inserted sorted array is:
2 3 4 6 8 10
*/
#include<stdio.h>
int insertSorted(int *a,int *size,int item);
int main()
{
int n,i;
int a[]={2,4,6,8,10};
printf("Original sorted array is:\n");
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter element to insert:\n");
scanf("%d",&n);
int size=5;
insertSorted(a,&size,n);
printf("\nAfter Inserted sorted array is:\n");
for(i=0;i<=5;i++)
{
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
int insertSorted(int *a,int *size,int item)
{
int i,j;//i is position
if(*size<0) {printf("Enter a positive array size.\n"); return;}
/*Determine the location to insert.*/
if(item<a[0])
{
i=0;
}
else
{
for(i=1;i<*size;i++)
{
if(( item<=a[i]) && (item>=a[i-1]))
{
break;//come out of the loop when right position
}
}
}
/*Shift the elemets after the position to insrt to right*/
for(j=*size;j>=i;j--)
a[j]=a[j-1];
/*Insert the lement at rigt postion*/
a[i]=item;
(*size)++;
}
/*
Original sorted array is:
2 4 6 8 10
Enter element to insert:
11
After Inserted sorted array is:
2 4 6 8 10 11
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
1
After Inserted sorted array is:
1 2 4 6 8 10
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
33
After Inserted sorted array is:
2 4 6 8 10 33
[user02@localhost ds]$ ./a.out
Original sorted array is:
2 4 6 8 10
Enter element to insert:
3
After Inserted sorted array is:
2 3 4 6 8 10
*/