Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Inserting a number into a sorted array (http://www.go4expert.com/articles/inserting-sorted-array-t2093/)

Inserting a number into a sorted array

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: C

`/*  **    To insert an inputed number into a previously sorted array,   **    at such a location so that the array remains sorted.  **    @author: Pradeep  **    @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]);  }`

 rahul.mca2001 6Mar2008 13:54

Re: Inserting a number into a sorted array

its a quite common problem

 All times are GMT +5.5. The time now is 21:10.