Embed presentation
Download to read offline
![/* PROGRAM FOR INSERTION SORTING IN ARRAY */
#include<iostream.h>
#include<conio.h>
#include<limits.h>
void insertionsort(int [], int);
void main()
{ clrscr();
int ar[40],item,n,index;
cout<<"n ENTER DESIRED ARRAY SIZE :- ";
cin>>n;
cout<<"n ENTER ARRAY ELEMENTS :- ";
for(int i=0;i<n;i++)
cin>>ar[i];
insertionsort(ar,n);
cout<<"n THE SORTED ARRAY IS AS SHOWN BELOW....n ";
for(i=0;i<n;i++)
cout<<" "<<ar[i]<<" ";
getch();
}
void insertionsort(int ar[],int size)
{ int tmp,j;
for(int i=0;i<size;i++)
{ j=i;
while(j>0 && (ar[j]<ar[j-1]))
{ tmp=ar[j];
ar[j]=ar[j-1];
ar[j-1]=tmp;
j--;
}
}
}
OUTPUT:-](https://image.slidesharecdn.com/insertio-220215071558/75/PROGRAM-FOR-INSERTION-SORTING-IN-ARRAY-1-2048.jpg)
This C++ program uses insertion sort to sort elements in an integer array. It takes user input for the array size and elements, calls the insertion sort function to sort the array, and then displays the sorted array output. The insertion sort function iterates through the array, compares each element to its preceding element, and swaps them if out of order, sorting the array in-place.
![/* PROGRAM FOR INSERTION SORTING IN ARRAY */
#include<iostream.h>
#include<conio.h>
#include<limits.h>
void insertionsort(int [], int);
void main()
{ clrscr();
int ar[40],item,n,index;
cout<<"n ENTER DESIRED ARRAY SIZE :- ";
cin>>n;
cout<<"n ENTER ARRAY ELEMENTS :- ";
for(int i=0;i<n;i++)
cin>>ar[i];
insertionsort(ar,n);
cout<<"n THE SORTED ARRAY IS AS SHOWN BELOW....n ";
for(i=0;i<n;i++)
cout<<" "<<ar[i]<<" ";
getch();
}
void insertionsort(int ar[],int size)
{ int tmp,j;
for(int i=0;i<size;i++)
{ j=i;
while(j>0 && (ar[j]<ar[j-1]))
{ tmp=ar[j];
ar[j]=ar[j-1];
ar[j-1]=tmp;
j--;
}
}
}
OUTPUT:-](https://image.slidesharecdn.com/insertio-220215071558/75/PROGRAM-FOR-INSERTION-SORTING-IN-ARRAY-1-2048.jpg)