adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C and C++ to insert element in an array in sorted order

Program in C and C++ to insert element in an array in sorted order second method


C Code
#include<stdio.h>
#include<conio.h>
#define size 35
 void insert_sorted(int A[],int *n,int data)
  {
      int i,loc;
      if(*n==size-1)
      {
          printf("Array is full!");
          return;
      }
      //If array is empty then data are store at 0th index
      if(*n==-1)
      {
          A[++(*n)]=data;
          return;
      }
   /*if data is greater than equals to last index data 
   then data are store after the last index
   */
    if(data>=A[*n])
        {
          A[++(*n)]=data;
           return;
        }
      for(i=*n;i>=0;i--)
       {
          if(data<=A[i])
              {
                  A[i+1]=A[i];
                  loc=i;
              }
          else 
            break;
        }
        A[loc]=data;
        (*n)++;
  }
 int main()
  {
    int a[size],n=-1,i;
    insert_sorted(a,&n,40);
    insert_sorted(a,&n,30);
    insert_sorted(a,&n,50);
    insert_sorted(a,&n,25);
    insert_sorted(a,&n,5);
    insert_sorted(a,&n,25);
    insert_sorted(a,&n,15);

    printf("Inserted elements are in ascending order \n");
    for(i=0;i<=n;i++)
         printf("%3d",a[i]);
    getch();
  }
CPP Code
/*insert data in an array in sorted order */
#include<iostream>
#include<conio.h>
 using namespace std;
 const int size=35;
 void insert_sorted(int A[],int *n,int data)
  {
      int i,loc;
      if(*n==size-1)
      {
          printf("Array is full!");
          return;
      }
      //If array is empty then data are store at 0th index
      if(*n==-1)
      {
          A[++(*n)]=data;
          return;
      }
   /*if data is greater than equals to last index data 
   then data are store after the last index
   */
    if(data>=A[*n])
        {
          A[++(*n)]=data;
           return;
        }
      for(i=*n;i>=0;i--)
       {
          if(data<=A[i])
              {
                  A[i+1]=A[i];
                  loc=i;
              }
          else 
            break;
        }
        A[loc]=data;
        (*n)++;
  }
 int main()
  {
    int a[size],n=-1,i;
    insert_sorted(a,&n,50);
    insert_sorted(a,&n,30);
    insert_sorted(a,&n,20);
    insert_sorted(a,&n,25);
    insert_sorted(a,&n,99);
    insert_sorted(a,&n,9);
    insert_sorted(a,&n,15);
    cout<<"Inserted elements are in ascending order \n"<<n;
    for(i=0;i<=n;i++)
         cout<<"   "<<a[i];
    getch();
  }
Output :-










Post a Comment

0 Comments