You are on page 1of 2

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment – 2.2
Student Name: Pratham Jain UID: 21BCS6915
Branch: CSE Section/Group: 813-A
Semester: 3rd Date of Performance:10-10-22
Subject Name: Data Structures Subject Code: 21CSH-211

Aim of the practical:


Write a program to sort an array of integers in ascending/descending order using a) Insertion
sort.

Algorithm:
1. Read ARRAY
2. Repeat step 3 to 8 for I=1 to N-1
3. Set Temp=ARRAY[I]
4. Set J=I-1
5. Repeat step 6 and 7 while Temp<ARRAY[J] AND J>=0
6. Set ARRAY[J+1]=ARRAY[J] [Moves element forward]
7. Set J=J-1
[End of step 5 inner
loop]
8. Set ARRAY[J+1]=Temp [Insert element in proper place]
[End of step 2 outer
loop]
9. Exit

Program Code:
#include<iostream>
using namespace std;
int main()
{
int arr[50], tot, i, j, k, elem, index;
cout<<"Enter the Size for Array: ";
cin>>tot;
cout<<"Enter "<<tot<<" Array Elements: ";
for(i=0; i<tot; i++)
cin>>arr[i];
for(i=1; i<tot; i++)
{
elem = arr[i];
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

if(elem<arr[i-1])
{
for(j=0; j<=i; j++)
{
if(elem<arr[j])
{
index = j;
for(k=i; k>j; k--)
arr[k] = arr[k-1];
break;
}
}
}
else
continue;
arr[index] = elem;
}
cout<<"\nThe New Array (Sorted Array):\n";
for(i=0; i<tot; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}

Output:

Learning outcomes:

1. Learned sorting using Insertion sort.


2. Learned to sort an array.
3. Concepts of Insertion Sort.

You might also like