1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Inserting a number into a sorted array

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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.
      **    @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]);
      }
     
  2. rahul.mca2001

    rahul.mca2001 New Member

    Joined:
    Feb 13, 2008
    Messages:
    103
    Likes Received:
    0
    Trophy Points:
    0
    its a quite common problem
     

Share This Page