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 sort an array using Insertion sort technique

Program in C and C++ to sort an array using Insertion sort technique


C PROGRAM
#include<stdio.h>
#include<conio.h>
#define size 35
 void instion_sort(int a[],int n);
 void main()
 {
     int i,a[size],n;
     printf("Enter the size of array:-");
     scanf("%d",&n);
     if(n>size)
       {
        printf("Invalid size of array.");
        return;
    }
  printf("Enter %d numbers:-",n); 
     for(i=0;i<n;i++)
       scanf("%d",&a[i]);
      
     printf("Elements of array before sorting.\n"); 
     for(i=0;i<n;i++){
        printf("%3d",a[i]);
  }
  instion_sort(a,n);
  printf("\nElements of array after sorting.\n"); 
     for(i=0;i<n;i++){
        printf("%3d",a[i]);
  }
     getch();
 }
 void instion_sort(int a[],int n)
  {
      int temp,i,j;
      for(i=1;i<n;i++)
       {
        temp=a[i];
         for(j=i-1;j>=0&&temp<a[j];j--)
           {
             a[j+1]=a[j];
           }
           a[j+1]=temp;
         }
  }
C++ PROGRAM
#include<iostream>
#include<conio.h>
using namespace std;
const int size=35;
 void instion_sort(int a[],int n);
 int main()
 {
     int i,a[size],n;
     cout<<"Enter the size of array:-";
     cin>>n;
     if(n>size)
       {
        cout<<"Invalid size of array.";
        return 0;
    }
  cout<<"Enter "<<n<<" numbers:-"; 
     for(i=0;i<n;i++)
       cin>>a[i];
      
     cout<<"Elements of array before sorting.\n"; 
     for(i=0;i<n;i++){
        cout<<"  "<<a[i];
  }
  instion_sort(a,n);
  cout<<"\nElements of array after sorting.\n"; 
     for(i=0;i<n;i++){
        cout<<"  "<<a[i];
  }
     getch();
 }
 void instion_sort(int a[],int n)
  {
      int temp,i,j;
      for(i=1;i<n;i++)
       {
        temp=a[i];
         for(j=i-1;j>=0&&temp<a[j];j--)
           {
             a[j+1]=a[j];
           }
           a[j+1]=temp;
         }
  }
Output :-






Related programs
  • Program in C and C++ to sort an array using Bubble sort technique
  • Program in C and C++ to sort an array using Selection sort technique
  • Program in C and C++ to sort an array using Quick sort technique
  • Program in C and C++ to sort an array using Enter change sort technique



Post a Comment

0 Comments