CSE DAA LAB MANUAL
CSE DAA LAB MANUAL
Objective:
Appendices
I. Institute Vision
II. Institute Mission
III. CSE Department Vision
IV CSE Department Mission
V CSE Department PEOs
VI Program Outcomes (POs)
PRACTICAL-1
OBJECT– TO IMPLEMENT THE INSERTION SORT.
efficient for data sets that are already substantially sorted: the running time is O(n
+ d), where d is the number of inversions
more efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms
such as selection sort or bubble sort: the average running time is n2/4, and the
running time is linear in the best case
stable (i.e., does not change the relative order of elements with equal keys)
in-place (i.e., only requires a constant amount O(1) of additional memory space)
online (i.e., can sort a list as it receives it)
Program –
#include<stdio.h>
#include<conio.h>
Void main()
{
int arr[5]={25,23,17,14,89};
int i,j,k,temp;
clrscr();
printf("INSERTION SORT \n\n");
printf("array before sorting :");
for(i=0;i<5;i++)
printf("%d\t",arr[i]);
for(i=1;i<5;i++)
{
for(j=0;j<i;j++)
{
if(arr[j]>arr[i])
{
temp=arr[j];
arr[j]=arr[i];
for(k=i;k>j;k--)
arr[k]=arr[k-1];
arr[k+1]=temp;
}
}
}
printf("\n\n array after sorting :");
for(i=0;i<5;i++)
printf("%d\t",arr[i]);
getch();
}
OUTPUT –
INSERTION SORT
array before sorting :
array after sorting :
PRACTICAL-2
Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-
lists.
The base cases of the recursion are lists of size zero or one, which are always sorted.
Program –
#include<stdio.h>
#include<conio.h>
void quicksort(int,int);
int partition(int,int);
int arr[10]={11,2,9,13,57,25,17,1,90,3};
void main()
{ int i;
clrscr();
printf("QUICK SORT\n");
printf("array before sorting :");
for(i=0;i<10;i++)
printf("%d ",arr[i]);
quicksort(0,9);
printf("\narray after sorting :");
for(i=0;i<10;i++)
printf("%d ",arr[i]);
getch(); }
void quicksort(int p,int q)
{
int i;
if(q>p)
{
i=partition(p,q);
quicksrt(p,i-1);
quicksort(i+1,q);
}
}
int partition(int p,int q)
{
int i=arr[p],t;
while(q>=p+1)
{
while(arr[p]<i)
p++;
while(arr[q]>i)
q--;
if(q>p+1)
{
t=arr[p+1];
arr[p+1]=arr[q];
arr[q]=t;
}
}
t=arr[p];
arr[p]=arr[q];
return q;
}
PRACTICAL-3
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm
and time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) +
The above recurrence can be solved either using Recurrence Tree method or Master method.
It falls in case II of Master Method and solution of the recurrence is .
Time complexity of Merge Sort is in all 3 cases (worst, average and best) as
merge sort always divides the array in two halves and take linear time to merge two halves.
Auxiliary Space: O(n)
Algorithmic Paradigm: Divide and Conquer
Sorting In Place: No in a typical implementation
Stable: Yes
Program
#include<stdlib.h>
#include<stdio.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
Output:
PRACTICAL-4
arr[] = 64 25 12 22 11
11 25 12 22 64
PROGRAM
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output:
PRACTICAL-5
Heapsort inserts the input list elements into a heap data structure. The largest value (in a
max-heap) or the smallest value (in a min-heap) are extracted until none remain, the
values having been extracted in sorted order. The heap's invariant is preserved after each
extraction, so the only cost is that of extraction.
During extraction, the only space required is that needed to store the heap. In order to
achieve constant space overhead, the heap is stored in the part of the input array that has
not yet been sorted.
(The structure of this heap is described at Binary heap:
Heap Implementation.)
Heapsort uses two heap operations: insertion and root deletion. Each extraction places an
element in the last empty location of the array. The remaining prefix of the array stores
the unsorted elements.
Program -
#include<stdio.h>
#include<conio.h>
void quicksort(int,int);
int partition(int,int);
int arr[10];
void main()
{
int i;
clrscr();
printf("QUICK SORT \n\n");
printf("enter the array");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
quicksort(1,10);
printf("the sorted array is :");
for(i=0;i<10;i++)
printf("%d\t",arr[i]);
getch();
}
void quicksort(int p,int r)
{
int q;
if(p<r)
{
q=partition(p,r);
quicksort(p,q-1);
quicksort(q+1,r);
}
}
int partition(int p,int r)
{
int x,i,j,temp;
x=arr[r];
i=p-1;
for(j=p;j<r;j++)
{
if(arr[j]<=x)
{
i++;
temp=arr[i];
arr[i]=arr[j];
}
}
temp=arr[r];
arr[r]=arr[i+1];
arr[i+1]=temp;
return(i+1);
}
OUTPUT – Enter the array:
The sorted array is :
PRACTICAL-6
THEORY – Given a sorted array arr[] of n elements, write a function to search a given
element x in arr[].
A simple approach is to do linear search.The time complexity of above algorithm is
O(n). Another approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
Begin with an interval covering the whole array. If the value of the search key is less
than the item in the middle of the interval, narrow the interval to the lower half.
Otherwise narrow it to the upper half. Repeatedly check until the value is found or the
interval is empty.
3. Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.
PROGRAM:
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
Output :
PRACTICAL-7
THEORY – In Fractional Knapsack, we can break items for maximizing the total value of
knapsack. This problem in which we can break an item is also called the fractional knapsack
problem.
Input :
Same as above
Output :
An efficient solution is to use Greedy approach. The basic idea of the greedy approach is to
calculate the ratio value/weight for each item and sort the item on basis of this ratio. Then
take the item with the highest ratio and add them until we can’t add the next item as a whole
and at the end add the next item as much as we can. Which will always be the optimal
solution to this problem.
A simple code with our own comparison function can be written as follows, please see sort
function more closely, the third argument to sort function is our comparison function which
sorts the item according to value/weight ratio in non-decreasing order.
After sorting we need to loop over these items and add them in our knapsack satisfying
above-mentioned criteria.
As main time taking step is sorting, the whole problem can be solved in O(n log n) only.
PROGRAM
// C++ program to solve fractional Knapsack Problem
#include <bits/stdc++.h>
using namespace std;
// Structure for an item which stores weight and corresponding
// value of Item
struct Item
{
int value, weight;
// Constructor
Item(int value, int weight) : value(value), weight(weight)
{}
};
// Comparison function to sort Item according to val/weight ratio
bool cmp(struct Item a, struct Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
double fractionalKnapsack(int W, struct Item arr[], int n)
{
sort(arr, arr + n, cmp);
// Uncomment to see new order of Items with their ratio /*
for (int i = 0; i < n; i++)
{
cout << arr[i].value << " " << arr[i].weight << " : "
<< ((double)arr[i].value / arr[i].weight) << endl;
}
*/
int curWeight = 0; // Current weight in knapsack
double finalvalue = 0.0; // Result (value in Knapsack)
for (int i = 0; i < n; i++)
{
if (curWeight + arr[i].weight <= W)
{
curWeight += arr[i].weight;
finalvalue += arr[i].value;
}
// If we can't add current Item, add fractional part of it
else
{
int remain = W - curWeight;
finalvalue += arr[i].value * ((double) remain / arr[i].weight);
break;
}
}
return finalvalue;
}
Output :
PRACTICAL-8
THEORY – Travelling Salesman Problem (TSP): Given a set of cities and distance
between every pair of cities, the problem is to find the shortest possible route that visits
every city exactly once and returns back to the starting point.
Note the difference between Hamiltonian Cycle and TSP. The Hamiltoninan cycle
problem is to find if there exist a tour that visits every city exactly once. Here we know
that Hamiltonian Tour exists (because the graph is complete) and in fact many such tours
exist, the problem is to find a minimum weight Hamiltonian Cycle.
For example, consider the graph shown in figure on right side. A TSP tour in the graph
is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80.
The problem is a famous NP hard problem. There is no polynomial time know solution
for this problem.
1. Consider city 1 as the starting and ending point. Since route is cyclic, we can
consider any point as starting point.
2. Generate all (n-1)! permutations of cities.
3. Calculate cost of every permutation and keep track of minimum cost permutation.
4. Return the permutation with minimum cost.
PROGRAM
// CPP program to implement traveling salesman
// problem using naive approach.
#include <bits/stdc++.h>
using namespace std;
#define V 4
// update minimum
min_path = min(min_path, current_pathweight);
} while (next_permutation(vertex.begin(), vertex.end()));
return min_path;
}
PRACTICAL-9
It works as follows:
create a forest F (a set of trees), where each vertex in the graph is a separate tree
create a set S containing all the edges in the graph
while S is nonempty
remove an edge with minimum weight from S
if that edge connects two different trees, then add it to the forest, combining two
trees into a single tree
otherwise discard that edge
At the termination of the algorithm, the forest has only one component and forms
a minimum spanning tree of the graph.
This algorithm first appeared in Proceedings of the American Mathematical Society, pp.
48–50 in 1956, and was written by Joseph Kruskal.
Other algorithms for this problem include Prim's algorithm, Reverse-Delete algorithm,
and Boruvka's algorithm
Where E is the number of edges in the graph and V is the number of vertices, Kruskal's
algorithm can be shown to run in O(E log E) time, or equivalently, O(E log V) time, all
with simple data structures. These running times are equivalent because:
Program –
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct lledge
{
int v1,v2;
float cost;
struct lledge *next;
};
int stree[5],count[5],mincost;
struct lledge *kminstree(struct lledge*,int);
int getrval(int);
void combine(int,int);
void del(struct lledge*);
void main()
{
struct lledge *temp,*root;
int i;
clrscr();
root=(struct lledge*)malloc(sizeof(struct lledge));
root->v1=4;
root->v2=3;
root->cost=1;
temp=root->next=(struct lledge*)malloc(sizeof(struct lledge));
temp->v1=4;
temp->v2=2;
temp->cost=2;
temp->next=(struct lledge*)malloc(sizeof(struct lledge));
temp=temp->next;
temp->v1=3;
temp->v2=2;
temp->cost=3;
temp->next=(struct lledge*)malloc(sizeof(struct lledge));
temp=temp->next;
temp->v1=4;
temp->v2=1;
temp->cost=4;
temp->next=NULL;
root=kminstree(root,5);
for(i=1;i<=4;i++)
printf("\n stree[%d]->%d",i,stree[i]);
printf("\n the minimum cost of spanning tree is %d ",mincost);
del(root);
getch();
}
struct lledge* kminstree(struct lledge *root,int n)
{
struct lledge *temp=NULL;
struct lledge *p,*q;
int noofedges=0;
int i,p1,p2;
for(i=0;i<n;i++)
stree[i]=i;
for(i=0;i<n;i++)
count[i]=0;
while((noofedges<(n-1))&&(root!=NULL))
{
p=root;
root=root->next;
p1=getrval(p->v1);
p2=getrval(p->v2);
if(p1!=p2)
{
combine(p->v1,p->v2);
noofedges++;
mincost+=p->cost;
if(temp==NULL)
{
temp=p;
q=temp;
}
else
{
q->next=p;
q=q->next;
}
q->next=NULL;
}
}
return temp;
}
int getrval(int i)
{
int j,k,temp;
k=i;
while(stree[k]!=k)
k=stree[k];
j=i;
while(j!=k)
{
temp=stree[j];
stree[j]=k;
j=temp;
}
return k;
}
void combine(int i,int j)
{
if(count[i]<count[j])
stree[i]=j;
else
{
stree[j]=i;
if(count[i]==count[j])
count[j]++;
}
}
void del(struct lledge *root)
{
struct lledge *temp;
while(root!=NULL)
{
temp=root->next;
free(root);
root=temp;
}
}
OUTPUT –
PRACTICAL-10
THEORY – We have discussed Knight’s tour and Rat in a Maze problems in Set
1 and Set 2 respectively. Let us discuss N Queen as another example problem that can be
solved using Backtracking.
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other. For example, following is a solution for 4 Queen problem.
The expected output is a binary matrix which has 1s for the blocks where queens are placed.
For example, following is the output matrix for above 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this row
and column as part of the solution. If we do not find such a row due to clashes then we
backtrack and return false.
PROGRAM
/* C/C++ program to solve N Queen Problem using backtracking */
#define N 4
#include<stdio.h>
bool solveNQ()
{
int board[N][N] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if ( solveNQUtil(board, 0) == false )
{
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
// driver program to test above function
int main()
{
solveNQ();
return 0;
}
Output:
AMBALIKA INSTITUTE OF MANAGEMENT & TECHNOLOGY, LUCKNOW
DEPARTMENT OF INFORMATION TECHNOLOGY
To nourish the students, blossom them into tomorrow’s world class professionals and good human
beings by inculcating the qualities of sincerity, integrity and social ethics.
1. To provide the finest infra structure and excellent environment for the academic growth of the
students to bridge the gap between academia and the demand of industry.
2. To expose students in various co- curricular activities to convert them into skilled professionals.
3. To grind very enthusiastic engineering and management student to transform him into hard
working, committed, having zeal to excel, keeping the values of devotion, concern and honesty.
To embrace students towards becoming computer professionals having problem solving skills,
leadership qualities, foster research & innovative ideas inculcating moral values and social concerns
PEO1:- All the graduates will become high class software professionals who could be absorbed in the
software industry on the basis of sound academic and technical knowledge gained by them on account
of adopting state of the art academic practices.
PEO2:-All the graduates will demonstrate their talent in research and development activities involving
themselves in such researches which could alleviate the existing problem of the society.
PEO3:-All the graduates shall be committed for high moral and ethical standards in solving the societal
problems by means of their exposure to various co-curricular and extra-curricular activities.
PROGRAM OUTCOME