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 elements in an array in sorted ascending order

Program in C and C++ to insert elements in an array in sorted ascending order

C PROGRAM
#include<stdio.h>
#include<conio.h>
#define size 35
 void insert_sorted(int A[],int *n,int data)
  {
      int i,loc=0,flag=0;
      if(*n==size-1)
      {
          printf("Array is full!");
          return;
      }
      if(*n==-1)
      {
          A[++(*n)]=data;
          return;
      }

      for(i=*n;i>=0;i--)
       {
          if(A[i]>data)
              {
                  flag=1;
                  A[i+1]=A[i];
                  loc=i;
              }
          else if(A[i]<data)
              {
                  A[i+1]=data;
                  (*n)++;
                  return;
              }
        }
       if(flag==1)
           {
               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,15);

    printf("Inserted elements are in ascending order \n");
    for(i=0;i<=n;i++)
         printf("%3d",a[i]);
    getch();
  }
C++ PROGRAM
#include<iostream>
#include<conio.h>
 using namespace std;
const int size=35;
 void insert_sorted(int A[],int *n,int data)
  {
      int i,loc=0,flag=0;
      if(*n==size-1)
      {
          cout<<"Array is full!";
          return;
      }
      if(*n==-1)
      {
          A[++(*n)]=data;
          return;
      }

      for(i=*n;i>=0;i--)
       {
          if(A[i]>data)
              {
                  flag=1;
                  A[i+1]=A[i];
                  loc=i;
              }
          else if(A[i]<data)
              {
                  A[i+1]=data;
                  (*n)++;
                  return;
              }
        }
       if(flag==1)
           {
               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";
    for(i=0;i<=n;i++)
         cout<<"   "<<a[i];
    getch();
  }
Output:-







Post a Comment

0 Comments