Showing posts with label Insertion Sort. Show all posts
Showing posts with label Insertion Sort. Show all posts

Friday, 1 September 2017

Insertion Sort Array C++ Program in Efficient Way

#include<bits/stdc++.h> //to include all header file
using namespace std;
main()
{
int n,i,j,k;
cout<<"Enter Size of Array:";
cin>>n;

int a[n];

cout<<"Enter Elements Into Array:";
for(i=0;i<n;i++)
cin>>a[i];

for(i=0;i<n-1;i++)
{
j=i;
while(j>=0&&a[j]<a[j+1])
{
swap(a[j],a[j+1]); //pre-defined function in STL
j--;
}
}
for(i=0;i<n;i++)
{
cout<<a[i];
}
}

Tuesday, 14 March 2017

Insertion In Array by Pointers C++ Program Exampe

#include<iostream>
using namespace std;
#include<conio.h>
 main()
{
int num[50],n, num1, i, pos,*p;
cout<<"Enter Array Size : ";
cin>>n;
cout<<"Enter Numbers : ";
for(i=0; i<n; i++)
cin>>num[i];
p=num;
cout<<"Enter Number to be inserted : ";
cin>>num1;
cout<<"Enter position :";
cin>>pos;
for(i=n; i>pos; i--)
{
*(p+i)=*(p+i-1);
}
*(p+pos)=num1;
for(i=0; i<n+1; i++)
{
cout<<*(p+i)<<" ";
}
getch();
}


Amazon1Ads