You are on page 1of 7

Maharaja Surajmal Institute of Technology

Algorithms Design and Analysis Lab

{Paper Code: ETCS-351}

Submitted to: Submitted by:


Dr. Nishtha Jatana Name: Shresth
Kumar
Assistant Professor E.no: 04396302720
CSE Department Branch: CSE-E
Semester: 5th
INDEX
S.no Experiment Name Sign
Experiment – 1
Aim: To implement Insertion sort algorithm using array as a data structure and analyse
its time complexity.

Code:
#include <bits/stdc++.h>
#include<iostream>
#include <chrono>
using namespace std;
void insertionSort(int arr[], int size)
{
int i, key, j;
auto start = chrono::steady_clock::now();
for (i = 1; i < size; i++) //c1
{
key = arr[i]; //c2
j = i - 1; //c3
while (j >= 0 && arr[j] > key) //c4
{
arr[j + 1] = arr[j]; //c5
j = j - 1; //c6
}
arr[j + 1] = key; //c7
}
auto end = chrono::steady_clock::now();
cout<<endl<<"Elapsed time in nanoseconds: "<<
chrono::duration_cast<chrono::nanoseconds>(end -
start).count()<< endl;;
}
void printArray(int arr[], int size)
{
int i;
cout<<"Sorted Array is : ";
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main()
{ cout<<"Enter Array size: ";
int size;
cin>>size;
int arr[100];
cout<<"Enter the array: ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
insertionSort(arr, size);
printArray(arr, size);
return 0;
}

Output:
BEST CASE

AVERAGE CASE

WORST CASE

You might also like