Professional Documents
Culture Documents
ASSIGNMENT#1
Name: Arbaz Ahmad Khan
Roll No: BCSM -F18-308
Subject: Design and Analysis of Algorithm
Class: BSCS
Section: 5A
Submitted To: Sir Imran
Page | 1
Design & Analysis of Algorithm
Code:
#include <iostream> using
namespace std;
int i, j, k; i = 0; j = 0; k
arr[k] = L[i];
i++; } else {
arr[k] = M[j];
j++;
k++;
Page | 2
Design & Analysis of Algorithm
arr[k] = M[j];
j++; k++;
if (l < r) {
1, r);
merge(arr, l, m, r);
endl;
Page | 3
Design & Analysis of Algorithm
Page | 4
Design & Analysis of Algorithm
Output:
Enter the number of elements to be sorted:10
Sorted array
11 12 13 23 24 32 54 74 81 105
Page | 5
Design & Analysis of Algorithm
We compare each element with all its previous elements and put or insert the
element in its proper position. Insertion sort technique is more feasible for arrays
with a smaller number of elements. It is also useful for sorting linked lists.
General Algorithm
C++ Implementation
Code:
#include<iostream>
using namespace std;
int main ()
{
int myarray[10] = { 12,4,3,1,15,45,33,21,10,2};
cout<<"\nInput list is \n"; for(int i=0;i<10;i++)
{
Page | 6
Design & Analysis of Algorithm
cout <<myarray[i]<<"\t";
}
for(int k=1; k<10; k++)
{
int temp = myarray[k];
int j= k-1;
while(j>=0 && temp <= myarray[j])
{
myarray[j+1] = myarray[j];
j = j-1;
}
myarray[j+1] = temp;
}
cout<<"\nSorted list is \n";
for(int i=0;i<10;i++)
{
cout <<myarray[i]<<"\t";
}
}
Page | 7