# Inserting a number into a sorted array

Discussion in 'C' started by pradeep, Dec 1, 2006.

Joined:
Apr 4, 2005
Messages:
1,646
86
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
When I was learning to C, our proffessor had given us a problem where we had to enter a number into a sorted array so that the array remains sorted even after the insertion.
So, I tried it yesterday, here's the code for it.

Code:
```/*
**    To insert an inputed number into a previously sorted array,
**    at such a location so that the array remains sorted.
**    @date: 11/30/2006
*/

#include <stdio.h>
/*define the size of the array*/
#define MAX_SIZE 6

void main(void)
{
int a[MAX_SIZE] = {2,6,12,15,18}; // fill sorted data into the array of size MAX_SIZE-1
int n,i,j;

printf("Enter the number to insert : ");
scanf("%d",&n);

for(i=0;i<MAX_SIZE-1;i++)
{
/* check for the location, which if found, shift numbers to the right */
if(a[i]>n)
{
for(j=MAX_SIZE-1;j>=i;j--)
a[j] = a[j-1];

break;
}

}

a[i] = n; // put the no. at the correct location

/* print the completed array */
for(i=0;i<MAX_SIZE;i++)
printf("%d ",a[i]);
}```

Joined:
Feb 13, 2008
Messages:
103