Inserting a number into a sorted array

pradeep's Avatar author of Inserting a number into a sorted array
This is an article on Inserting a number into a sorted array in C.
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]);
  }

Ambitious contributor
6Mar2008,13:54   #2
rahul.mca2001's Avatar
its a quite common problem