manual (1)
manual (1)
TECHNOLOGY, MEERUT
1
Vision and Mission Institute
Vision
Mission
The mission of the institute is to educate young aspirants in various technical fields to fulfill
global requirement of human resources by providing sustainable quality education, training
and invigorating environment besides molding them into skilled competent and socially
responsible citizens who will lead the ...
2
Vision and Mission of the Department
Vision
To be an excellent department that imparts value-based quality education and uplifts innovative research in the ever-
changing field of technology.
Mission
To fulfil the requirement of skilled human resources with focus on quality education.
To create globally competent and socially responsible technocrats by providing value and need based training.
To improve Industry-Institution Interaction and encourage the innovative research activities
3
Program Educational Objectives (PEOs)
Students will have the successful careers in the field of computer science and allied sectors as an
PEO 1
innovative engineer.
Students will continue to learn and advance their careers through participation in professional activities,
PEO 2
attainment of professional certification and seeking advance studies
PEO 3 Students will be able to demonstrate a commitment to life-long learning.
PEO 4 Students will be ready to serve society in any manner and become a responsible and aware citizen.
PEO 5 Establishing students in a leadership role in any field
Ability to apply and analyses computational concepts in the areas related to algorithms, machine
PSO 1
learning, cloud computing, web designing and web services.
Ability to apply standard practices and methodologies in software development and project
PSO 2
management.
Ability to employ fundamental concepts and emerging technologies for innovative research activities,
PSO 3
carrier opportunities & zeal for higher studies.
4
rogram Outcomes (POs)
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and safety, and
the cultural, societal, and environmental considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research methods including
design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT
tools including prediction and modeling to complex engineering activities with an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health,
safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering solutions in societal
and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams,
and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the engineering community
and with society at large, such as, being able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and
life-long learning in the broadest context of technological change.
5
Course Details
Name of the Course / Subject Design and analysis of algorithms
Subject / Course Code KCS-553 Theory / Lab Theory
Academic Session 2023-2024 Semester V
L T P 0-0-2 Credits 1
Core // Dept. / Open Elective Core Internal Marks 25
Total Marks of the Subject 50 External Marks 25
Name of the Faculty Dr. Waseem Ahmad
Class-room M302
Time-Table (mention lecture timings in appropriate cell)
Mon Tues Wed Thurs Fri
1:30-3:10,
- 10:50-12:30
6
COURSE TITLE: DESIGN AND ANALYSIS OF ALGORITHMS LAB
LAB OBJECTIVES:
COURSE PREREQUISITES: Expected Prior Knowledge and Skills: Proficiency in a C & C++
programming language, basic program design concepts (e. g, pseudo code), proof techniques,
familiarity with trees and graph data structures, familiarity with basic algorithms such as those for
searching, and sorting, knowledge of Discrete Structures as minimum cost spanning trees.
7
B. TECH (COMPUTER SCIENCE & ENGINEERING/ COMPUTER SCIENCE) CURRICULUM
STRUCTURE
SEMESTER- V
End
Sl. Subject Periods Evaluation Scheme
Subject Semeste Total Credit
No. r
Codes L T P CT TA Total PS TE PE
Design and Analysis of
1 KCS553 0 0 2 25 25 50 1
Algorithm Lab
8
Design and Analysis of Algorithm Lab (KCS-553)
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
DETAILED SYLLABUS
1. Program for Recursive Binary & Linear Search.
2. Program for Heap Sort.
3. Program for Merge Sort.
4. Program for Selection Sort.
5. Program for Insertion Sort.
6. Program for Quick Sort.
7. Knapsack Problem using Greedy Solution
8. Perform Travelling Salesman Problem
9. Find Minimum Spanning Tree using Kruskal’s Algorithm
10. Implement N Queen Problem using Backtracking
11. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus non
graph sheet. The elements can be read from a file or can be generated using the random number generator.
Demonstrate using Java how the divide and- conquer method works along with its time complexity analysis: worst
case, average case and best case.
12. Sort a given set of n integer elements using Merge Sort method and compute its time complexity. Run the
program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the time taken versus non
graph sheet. The elements can be read from a file or can be generated using the random number generator.
Demonstrate how the divide and- conquer method works along with its time complexity analysis: worst case,
average case and best case.
13. Implement , the 0/1 Knapsack problem using
(a) Dynamic Programming method (b)Greedy method.
14. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's
algorithm.
15. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's algorithm. Use
Union-Find algorithms in your program.
16. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.
17. Write programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
18. Design and implement to find a subset of a given set S = {Sl, S2, ................ ,Sn} of n positive integers whose
SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions
{1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution.
19. Design and implement to find all Hamiltonian Cycles in a connected undirected Graph G of n
vertices using backtracking principle
Note: The Instructor may add/delete/modify/tune experiments, wherever he/she feels in a justified manner
It is also suggested that open source tools should be preferred to conduct the lab ( C, C++etc)
9
Course Outcome (Design and Analysis of Algorithm Lab, KCS-553)
Revised Bloom’s Knowledge
Relevant POs/
CO No. Course Outcome (CO) Cognitive Process Category* (KC)
PSOs
Level (BL)
CO1 Implement algorithm to solve problems
PO2, PO4, PO12, Analyze, Apply C, P
byiterative approach.
CO2 Implement algorithm to solve problems PO2, PO4, PO5,
Analyze, Apply C, P
bydivide and conquer approach PO12,
PO1, PO3, PO5,
CO3 Implement algorithm to solve problems
PO11, PO12, Create P, M
by Greedy algorithm approach.
PSO2
Implement algorithm to solve problems
CO4 PO1, PO11,
byDynamic programming, backtracking Understand, Apply P, M
PO12,
approach.
CO1 - 3 - 2 - - - - - - - 3 - - -
CO2 - 3 - 3 2 - - - - - - 2 - - -
CO3 3 - 3 - 2 - - - - - 2 2 - 2 -
CO4 2 - - - - - - - - - 2 2 - - -
CO5 - - - - 2 - - - - - - 2 - - 1
10
Lesson Plan
11
Design Analysis of Algorithms
Definition: “The algorithm is a set of rules defined in specific order to do certain computation and carry
out some predefined task. It is a step by step procedure to solve the problem.”
Evolution of algorithm : The term Algorithm was coined by the Persian mathematician Al-
Khwarizmi in the ninth century.
Given the algorithm, it is easy to program the solution. It bridges the gap between natural language
description of the solution and syntax of programming language. It is a set of rules which are used to
solve real-life problems. It provides a loose form of a solution in a pseudo-programming language. We
can treat it as a set of finite instructions which solves a particular problem when applied it is applied to
that problem with legal inputs.
The first-ever algorithm was developed by Babylonians for factorization of a number and to find roots of
the equation. Euclid had proposed a famous algorithm for finding Greatest Common Divisor (GCD) of
two numbers.
Initially, the solution to the problem is thought as a natural language description, whose syntax is too far
from the programming language. Before the actual problem solved in a programming language, natural
language description of the solution is first represented as an algorithm. It is then converted to
programming syntax.
Properties of Algorithm
Input: The algorithm may take zero or more input arguments. Depending on the problem, the input may
be a scalar, vector, array, tree, graph or some other data structures
Output: The algorithm reads input, processes it and produces at least one output. Depending on the
12
problem being solved, the output may of the form scalar, vector, array, tree, graph or some other data
structures.
Definiteness: All instructions should be unambiguous and simple to interpret. There should not be
multiple ways to interpret the same instruction. Each instruction should be precise and concise
Finiteness: Every algorithm must terminate after a finite number of steps. If the algorithm contains a
loop, the upper bound of the loop must be finite. Recursive calls should have a well-defined base case for
the termination
Effectiveness: The algorithm should be written with a basic set of instructions. The operations should be
basic enough to perform exactly using a basic set, just like one can perform them with pen and paper.
Complex operations should be performed using a combination of basic instruction. For example,
multiplication should be performed using loop and addition, sorting should be carried out using looping,
comparison, swapping etc.
Types of Algorithmic Complexities
Algorithms are analyzed using two types of complexities
Such problems may not be solved effectively using traditional approaches and even if they are solvable,
the answer may not be optimal or it may take a too long time. Various class of algorithms are :
String matching algorithms: Can be useful in text search, editors, compilers etc.
Number theory and numerical algorithms: Useful in the statistical analysis of data.
Divide and conquer: Used to solve sorting, convex hull, min-max problem.
Linear programming: Can be useful in solving many optimization problems.
Dynamic programming: Solves the optimization problems like subsequence, super sequence,
assembly line scheduling, cruise scheduling etc.
Greedy methods: Provides a suboptimal solution to the problems like make a change, minimum
spanning tree, Huffman code, job sequencing etc.
13
Sorting: Useful to sort numerical or string data.
However, the list is far more exhaustive, but we listed here a few of the most common problems appear
in real life.
Head and body. Head part consists of name, description of the problem being solved, input to the
problem and expected output. It may also include the explanation of the input argument and output
variable. The description provides a clear idea to the user about the functionality of the algorithm.
Body part includes a logical sequence of statements involving various constructs like conditional
statements, expressions, loops, breaks, function calls etc.
Structure of Algorithm
An algorithm is a lucid form of program and it does not have rigid restrictions on the syntax. One can
write it using his own terminology and syntax
However, some of the common rules followed for writing algorithms, which are stated below:
The algorithm should start with the keyword Algorithm, followed by its name, followed by a list of
arguments to be passed.
Algorithm FIND_SUM(A, B)
Comments start with // sign. In the very next line, we should specify the description and input-
output.
// Problem Description : Add two integer numbers.
// Input: Two numbers A and B on which sum is to be performed.
// Output: Sum of given two numbers.
Next comes the body part, which contains various logical statements in the proper sequence. These
statements may contain control statements, loops, expressions etc.
Compound statements are enclosed within the opening and closing curly brace i.e. { … }
Use the left arrow for assignment
C←A+B
if (condition) then
Statements
end
if (condition) then
Statements
else
Statements
end
Sometimes curly braces are omitted and a block is closed with the end keyword
while (condition) do
Do some work
end
Sometimes curly braces are omitted and a block is closed with the end keyword
15
for index ← FirstIndex to LastIndex do
Do some work
end
Algorithm FACTORIAL(n)
// Description: Find factorial of a given number
// Input: Number n whose factorial is to be computed
// Output : Factorial of n = n x (n – 1) x … x 2 x 1
if (n == 1) then
return 1
else
return n * FACTORIAL(n – 1)
end
Algorithm Design:
The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space. To solve a problem, different
approaches can be followed. Some of them can be efficient with respect to time consumption,
whereas other approaches may be memory efficient. However, one has to keep in mind that both
time consumption and memory usage cannot be optimized simultaneously.
The Need for Analysis: Algorithms are often quite different from one another, though the
objectives of these algorithms are the same. Analysis of algorithm is theprocess of analyzing the
problem-solving capability of the algorithm in terms of the time and size required. Generally, the
following types of analysis are performed −
Worst-case − the maximum number of steps taken on any instance of size a.
Best-case − the minimum number of steps taken on any instance of size a.
Average case − the average number of steps taken on any instance of size a.
Asymptotic Notations: Execution time of an algorithm depends on the instruction set, processor
speed, disk I/O speed, etc. Hence, we estimate the efficiency of an algorithm asymptotically.
Different types of asymptotic notations are used to represent the complexity of an algorithm.
Following asymptotic notations are used to calculate the running time complexity of an algorithm.
O − Big Oh
Ω − Big omega
θ − Big theta
o − Little Oh
ω − Little omega
17
Algorithm Design Techniques: The following is a list of several popular design
approaches:
Recursive
Divide and Conquer
Dynamic Programming
Greedy Technique
Brute Force
Backtracking
Branch and Bound
Recursive Algorithm: This is one of the most interesting Algorithms as it calls itself
with a smaller value as inputs which it gets after solving for the current inputs. In simpler
words, it’s an Algorithm that calls itself repeatedly until the problem is solved.
Problems such as the Tower of Hanoi or DFS of a Graph can be easily solved by using
these Algorithms.
Divide and Conquer: This is another effective way of solving many problems. In
Divide and Conquer algorithms, divide the algorithm into two parts; the first parts divide
the problem on hand into smaller sub problems of the same type. Then, in the second
part, these smaller problems are solved and then added together (combined) to produce
the problem’s final solution.
Problems such as Binary Search, Quick Sort, and Merge Sort can be solved using this
technique.
Dynamic Programming: These algorithms work by remembering the results of the
past run and using them to find new results. In other words, a dynamic
programming algorithm solves complex problems by breaking them into multiple
simple sub problems and then it solves each of them once and then stores them for
future use. Dynamic Programming is frequently related to Optimization Problems.
Problems such as Multistage Graphs, Optimal Binary Search Tress can be solved
using this technique.
Greedy Technique: This is used to solve the optimization problem. Anoptimization
problem is one in which there is a given a set of input values, which are required either
to be maximized or minimized (known as objective), i.e. some constraints or conditions.
It always makes the choice (greedy criteria) looks best at the moment, to optimize a
given objective. It doesn't always guarantee the optimal solution however it generally
produces a solution that is very close in value to the optimal.
Problems such as Kruskal’s Minimum Spanning Tree (MST), Prim's Minimal Spanning
Tree, Dijkstra's Minimal Spanning Tree and Knapsack Problem can be solved using this
technique.
Brute Force Algorithm: This is one of the simplest algorithms in the concept. A brute
force algorithm blindly iterates all possible solutions to search one or more than one
solution that may solve a function. Think of brute force as using all possible
combinations of numbers to open a safe. Problems such as Selection Sort, convex hull
can be solved using this technique.
Backtracking Algorithm: Backtracking is a technique to find a solution to aproblem
in an incremental approach. It solves problems recursively and tries tosolve a
problem by solving one piece of the problem at a time. If one of thesolutions
fails, we remove it and backtrack to find another solution. In other words,a backtracking
algorithm solves a sub problem, and if it fails to solve the problem,it undoes the last 18
step and starts again to find the solution to the problem. N-Queens problem is one good
example to see Backtracking algorithm in action.
Branch and Bound: In Branch & Bound algorithm a given sub problem, which
cannot be bounded, has to be divided into at least two new restricted sub problems.
Branch and Bound algorithm are methods for global optimization in non-convex
problems. Branch and Bound algorithms can be slow, however in the worst casethey
require effort that grows exponentially with problem size.
19
Problem 1. Write a Program in C/C++ to implement Linear and Binary Search Algorithms.
(Recursion)
Algorithm:
LinearSearch (array, index, key):
if index < 0:
return -1;
if item = key:
return index
return LinearSearch (array, index-1, key)
#include <stdio.h>
int linearSearch(int arr[], int n, int s, int i) {
if (i == n)
return -1;
if (arr[i] == s)
return (i + 1);
else
linearSearch(arr, n, s, i + 1);
}
int main() {
int arr[10] = {12, 20, 23, 4, 9, 13, 1, 32, 5, 19};
int i, s, position;
printf("Enter the element to search: ");
scanf("%d", & s);
position = linearSearch(arr, 10, s, 0);
if (position == -1)
printf("%d can not be found!", s);
else
printf("%d has been found at position %d ", s, position);
return 0;}
20
Recursive Binary Search: Recursive function is a function which calls itself during its execution.
Recursive Binary Search is Working with the Sorted Array. if the array is not sorted then using Sorting
Algorithm make an Array to Sort. In Recursive Binary Search Compare start from the middle of array
if Searching Element is lower is middle goes to left side one by one, if the Searching Element is Greater
than the middle Element its goes right side one by one in recursive order. If found it Return its Index
which is 0 or above 0 and When number is not, it Return -1 as response.
Algorithm:
function binary_search(array[],length,search_number,lower,upper)
if(lower <= upper)
mid = (lower+upper)/2;
if(search_number == array[mid])
return mid
else if(search_number < array[mid])
return binary_search(array, length,search_number,lower,mid-1)
else
return binary_search(array, length,search_number,center+1,upper)
else
return -1
Main procedure
lower = 0
upper = length-1
search_number = 45
found = binary_search(array[], length, search_number, lower, upper)
if(found>-1)
Found having Index
else
Not Found
21
Program: Binary Search
#include <stdio.h>
int binarySearch(int arr[], int lo, int hi, int item)
{
int mid;
if (lo > hi)
return -1;
mid = (lo + hi) / 2;
if (arr[mid] == item)
return mid;
else if (arr[mid] > item)
binarySearch(arr, lo, mid - 1, item);
else if (arr[mid] < item)
binarySearch(arr, mid + 1, hi, item);
}
int main()
{
int arr[] = {1,4,5,9,12,13,19, 20, 23,32};
int index = 0;
int item = 0;
printf("Enter the element to search: ");
scanf("%d", &item);
index = binarySearch(arr, 0, 5, item);
if (index == -1)
printf("Element not found in present in the given list\n");
else
printf("Desired element is found at position %d\n", index+1);
return 0;
}
22
CO 1 Implement algorithm to solve problems by iterative approach.
Problem 2: Write a program in C/C++ to implement Selection Sort and Insertion Sort
algorithm. (CO1)
Selection Sort: Selection Sort is a simple comparison-based sorting algorithm. Its primary idea is to
divide the input list into two parts: a sorted sublist and an unsorted sublist. Initially, the sorted sublist is
empty, and the unsorted sublist contains all the elements. The algorithm repeatedly selects the smallest
(or largest, depending on the sorting order) element from the unsorted sublist and moves it to the end
of the sorted sublist. This process continues until the unsorted sublist is empty and the sorted sublist
contains all the elements in the desired order.
Algorithms:
SelectionSort(int A[], n)
int i, j, minIndex, temp;
for i = 0 to n - 1 do
minIndex = i
for j = i + 1 to n - 1 do
if arr[j] < arr[minIndex] then
minIndex = j
end if
end for
temp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = temp
end for
end procedure
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, temp;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
temp = arr[i];
arr[i] = arr[position];
arr[position] = temp;
} }
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;} 23
Insertion Sort: Insertion Sort is a sorting algorithm where the array is sorted by taking one
element at a time. The principle behind insertion sort is to take one element, iterate through the
sorted array & find its correct position in the sorted array. Insertion Sort works in a similar
manner as we arrange a deck of cards.
Algorithm:
void insertionSort(int array[], int n)
{
int i, element, j;
for (i = 1; i < n; i++) { element = array[i]; j = i – 1
while (j >= 0 && array[j] > element) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = element;
}
}
Program: Insertion Sort
#include <math.h>
#include <stdio.h>
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}}
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = {6, 12, 0, 18, 11,85, 99, 55, 45, 34, 2};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
24
CO 2 Implement algorithm to solve problems by divide and conquer approach
Problem 3: Write a program in C/C++ to implement merge Sort and Quick Sort algorithm.
(CO2)
Merge: Merge Sort is a Divide and Conquer algorithm. It divides the input array into two
halves, calls itself for the two halves, and then merges the two sorted halves. The Merge()
function is used for merging two halves. The Mergesort() is a key process that sorts the A[l..m]
and A[m+1..r] into two sorted sub-arrays.
Algorithm MergeSort(low,high)
// a[low :high]is a global array to be sorted. // Small(P)is true if there is only one element
to sort. In this case the list is already sorted.
{
if (low <high) then //If there are more than
one element
{
Divide P into sub problems.Find where to split the set.
mid:=[(low+high)/2];
Solve the sub problems.
MergeSort(low, mid);
MergeSort(mid+1 ,high);
Combine the solutions.
Merge(low,mid,high);
}
}
Algorithm Merge(low,mid,high)
a[low:high] is a global array containing two sorted ubsets in a[low:mid] and in
a[mid+1:high].The goal is to merge these two sets into a single set residing in a[low
:high]. b[ ]is an auxiliary global array.
{h :=low; i :=low; j :=mid+ 1;
while ((h <=mid) and (j <=
high)) do {
if (a[h] <=a[j]) then
{ b[i]:=a[h]; h :=h + 1; }
else
{ b[i] =a[j]; j :=j + l; }
i :=i +1; }
if (h >mid) then
for k :=j to high do
{
b[i] :=a[k]; i :=i +1;
}
else
for k :=h to mid do
{ b[i] :=a[k]; i :=i +1; }
for k:=low to high do
a[k] :=b[k];}
25
Program: Merge Sort
#include <stdio.h>
#define max 10
int a[11] = { 6, 12,0,18, 11,85,99,55,45, 34,2 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
int main() {
26
int i;
printf("List before sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}
Quick Sort:
Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions
the given array around the picked pivot. There are many different versions of quick Sort
that pick pivot in different ways.
Always pick first element as pivot.
Always pick last element as pivot (implemented below)
Pick a random element as pivot.
Pick median as pivot.
The key process in quick Sort is partition (). Target of partition() is, given an array and
an element x of array as pivot, put x at its correct position in sorted array and put all
smaller elements (smaller than x) before x, and put all greater elements (greater than x)
after x.
Algorithm Partition(a[],m,p)
//Within a[m],a[m+1],... ,a[p-1]the elements are rearranged in such a manner that if
initially t = a[m],4 then after completion a[q] = t for some q between m5 and p-1,a[k]
≤ t for m ≤ k < g, and a[k] ≥ t for q <k <p. q is returned. Set a[p] = ∞.
{
27
Algorithm Interchange (a[],i,j)
// Exchange a[i] with a[j].
{
p: =a[i];
a[i]:=a[j]; a[j]:=p;
}
Algorithm QuickSort(p, q)
// Sorts the elements a[p],..., a[q] hich reside in the global array a[l:n] into
ascending order; a[n+1]is considered to be defined and must be >= all the
elements in a[l:n].
{
if (p <q) then
{
divide P into two sub problems.
j :=Partition(a,p, q + 1);
QuickSort(p,j-1);
QuickSort(j+ l,q);
}
}
#include <stdio.h>
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
29
CO 3 Implement algorithm to solve problems by Greedy algorithm approach.
Problem 4(a): Write a Program in C/C++ to implement Fractional Knapsack. (CO3: Greedy
Approach)
Fractional Knapsack : It is defined as, “Given a set of items having some weight and
value/profit associated with it. The knapsack problem is to find the set of items such that the
total weight is less than or equal to a given limit (size of knapsack) and the total value/profit
earned is as large as possible.”
Given a set of items, each having some weight and value/profit associated with it. The goal is
to find the set of items such that the total weight is less than or equal to a given limit (size of
knapsack) and the total value/profit earned is as large as possible.
The knapsack is an optimization problem and it is useful in solving resource allocation
problem.
Let X = <x1, x2, x3, . . . . . , xn> is the set of n items. W = <w1, w2, w3, . . . , wn> and V =
<v1, v2, v3, . . . , vn> are the set of weight and value associated with each items in x,
respectively. Knapsack capacity is M.
Select items one by one from the set of items x and fill the knapsack such that it would
maximize the value. Knapsack problem has two variants. 0/1 knapsack does not allow breaking
of items. Either add entire item in a knapsack or reject it. It is also known as a binary knapsack.
Fractional knapsack allows the breaking of items. So profit will also be considered accordingly.
Knapsack problem can be formulated as follow:
Maximize
subjected to
30
Algorithms:
Algorithm GREEDY_FRACTIONAL_KNAPSACK(X, V, W, M)
// Description : Solve the knapsack problem using greedy approach
// Input:
X: An array of n items
V: An array of profit associated with each item
W: An array of weight associated with each item
M: Capacity of knapsack
// Output :
SW: Weight of selected items
SP: Profit of selected items
// Items are presorted in decreasing order of pi = vi / wi ratio
while i ≤ n do
if (SW + w[i]) ≤ M then
S ← S ∪ X[i]
SW ← SW + W[i]
SP ← SP + V[i]
else
frac ← (M - SW) / W[i]
S ← S ∪ X[i] * frac // Add fraction of item X[i]
SP ← SP + V[i] * frac // Add fraction of profit
SW ← SW + W[i] * frac // Add fraction of weight
end
i←i+1
end
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
printf("Knapsack problems using Greedy Algorithm:\n");
for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
} }
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}
Algorithm KUSKAL_MST(G)
// Description : Find minimum spanning tree of graph G of n vertices
// Input : Weighted undirected graph G
// Output : Minimum spanning tree of G
MST ← Φ
for each v ∈ V do
MAKE-SET(v)
end
for MAKE-SET(v) do
if FIND-SET(u) ≠ FIND-SET(v) then
MST ← MST ∪ (u, v)
UNION(u, v)
end
end
FUNCTION MAKE-SET(x)
if x is not already present then
x.parent ← x
x.rank ← 0
end
if x.parent ≠ x then
x.parent ← FIND(x.parent)
end
return x.parent
FUNCTION UNION(x, y)
xRoot ← FIND(x)
yRoot ← FIND(y)
if xRoot == yRoot then
return
end
#include <stdio.h>
#define MAX 30
typedef struct edge {
int u, v, w;
} edge;
typedef struct edge_list {
edge data[MAX];
int n;
} edge_list;
edge_list elist;
int Graph[MAX][MAX], n;
edge_list spanlist;
void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
void kruskalAlgo() {
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;
for (i = 1; i < n; i++)
for (j = 0; j < i; j++) {
if (Graph[i][j] != 0) {
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}
sort();
for (i = 0; i < n; i++)
belongs[i] = i;
spanlist.n = 0;
for (i = 0; i < elist.n; i++) {
cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);
if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
int find(int belongs[], int vertexno) { 34
return (belongs[vertexno]);
}
void applyUnion(int belongs[], int c1, int c2) {
int i;
for (i = 0; i < n; i++)
if (belongs[i] == c2)
belongs[i] = c1;
}
void sort() {
int i, j;
edge temp;
for (i = 1; i < elist.n; i++)
for (j = 0; j < elist.n - 1; j++)
if (elist.data[j].w > elist.data[j + 1].w) {
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp;
}
}
void print() {
int i, cost = 0;
for (i = 0; i < spanlist.n; i++) {
printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}
printf("\nSpanning tree cost: %d", cost);
}
int main() {
int i, j, total_cost;
n = 7;
Graph[0][0] = 0;
Graph[0][1] = 28;
Graph[0][2] = 0;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 10;
Graph[0][6] = 0;
Graph[2][0] = 0;
Graph[2][1] = 16;
Graph[2][2] = 0;
Graph[2][3] = 12;
Graph[2][4] = 0;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0; 35
Graph[3][2] = 12;
Graph[3][3] = 0;
Graph[3][4] = 22;
Graph[3][5] = 0;
Graph[3][6] = 18;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 0;
Graph[4][3] = 22;
Graph[4][4] = 0;
Graph[4][5] = 25;
Graph[4][6] = 24;
Graph[5][0] = 10;
Graph[5][1] = 0;
Graph[5][2] = 0;
Graph[5][3] = 0;
Graph[5][4] = 25;
Graph[5][5] = 0;
Graph[5][6] = 0;
Graph[6][0] = 0;
Graph[6][1] = 14;
Graph[6][2] = 0;
Graph[6][3] = 22;
Graph[6][4] = 24;
Graph[6][5] = 0;
Graph[6][6] = 0;
kruskalAlgo();
print();
}
Prim’s Algorithm: It is a greedy approach to find a minimum spanning tree from weighted,
connected, undirected graph. It is a variation of Dijkstra’s algorithm. Working principle of
Prim’s algorithm is very simple and explained here:
1. Select any arbitrary vertex from input graph G, call that subgraph as partial MST.
Remove selected vertex from UV
2. Form a set NE – a set of unvisited neighbour edges of all vertices present in partial MST
3. Select an edge e = (u, v) from NE with minimum weight, and add it to partial MST if it
does not form a cycle and it is not already added.
If the addition of edge e forms a cycle, then skip that edge and select next minimum weight
edge from NE. Continue this procedure until we get an edge e which does not form a cycle. 36
Remove corresponding added vertices u and v from UV
Algorithm PRIM_MST(G, n)
// Description : Find MST of graph G using Prim’s algorithm
// Input : Weighted connected graph G and number of vertices n
// Output : Minimum spanning tree MST and weight of it i.e. cost
cost ← 0
// Initialize tree nodes
for i ← 0 to n – 1 do
MST[i] ← 0
end
for k ← 1 to n do
min_dist ← ∞
for i ← 1 to n – 1 do
for j ← 1 to n – 1 do
if G[i, j] and ((MST[i] AND ¬MST[j]) or (¬MST[i] AND MST[j])) then
if G[i, j] < min_dist then
min_dist ← G[i, j]
u←i
v←j
end
end
end
end
38
Implement algorithm to solve problems by Dynamic programming,
CO 4 backtracking.
Problem 5(a). Write a program in C/C++ to implement, the 0/1 Knapsack problem using
Dynamic Programming method.(CO4:Dynamic Programming method)
Introduction to 0/1 Knapsack Problem : Given a set of items, each having different weight and
value or profit associated with it. Find the set of items such that the total weight is less than or
equal to a capacity of the knapsack and the total value earned is as large as possible. The
knapsack problem is useful in solving resource allocation problem. Let X = < x1, x2, x3, . . . .
. , xn> be the set of n items. Sets W = <w1, w2, w3, . . . , wn> and V = < v1, v2, v3, . . . , vn>
are weight and value associated with each item in X. Knapsack capacity is M unit.The knapsack
problem is to find the set of items which maximizes the profit such that collective weight of
selected items does not cross the knapsack capacity. Select items from X and fill the knapsack
such that it would maximize the profit. Knapsack problem has two variations. 0/1 knapsack,
that does not allow breaking of items. Either add an entire item or reject it. It is also known as
a binary knapsack. Fractional knapsack allows breaking of items. Profit will be earned
proportionally.
If the weight of the item is larger than the remaining knapsack capacity, we skip the item, and
the solution of the previous step remains as it is. Otherwise, we should add the item to the
solution set and the problem size will be reduced by the weight of that item. Corresponding
profit will be added for the selected item.
Dynamic programming divides the problem into small sub-problems. Let V is an array of the
solution of sub-problems. V[i, j] represents the solution for problem size j with first i items.
The mathematical notion of the knapsack problem is given as :
for i ← 1 to n do
V[i, 0] ← 0
end
for i ← 1 to M do
V[0, i] ← 0
end
for V[0, i] ← 0 do
for j ← 0 to M do
if w[i] ≤ j then
V[i, j] ← max{V[i-1, j], v[i] + V[i – 1, j – w[i]]}
else
V[i, j] ← V[i – 1, j] // w[i]>j
end
end
end
Algorithm TRACE_KNAPSACK(w, v, M)
// w is array of weight of n items
// v is array of value of n items
// M is the knapsack capacity
SW ← { }
SP ← { }
i←n
j←M
while ( j> 0 ) do
if (V[i, j] == V[i – 1, j]) then
i←i–1
else
V[i, j] ← V[i, j] – vi
j ← j – w[i]
SW ← SW +w[i]
SP ← SP +v[i]
end
end
40
Program: Implementation of 0/1 Knapsack in C
#include<stdio.h>
#include<conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value; if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
int main()
{
int profit,count=0;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{ 41
x[i]=1;
j=j-w[i]; i--;
}
else i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i]) printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
return 0;
}
Problem 5(b). Write a program in C/C++ to implement N Queen problem (CO4:
Backtracking).
N Queen Problem: N-Queen Problem: N Queen's problem: The n-queens problem consists of placing
n queens on an n x n chessboard so that no two queens attack each other by being in the same row or
in the same column or on the same diagonal. The queens are arranged in such a way that they do not
threaten each other, according to the rules of the game of chess. Every queen on a chessboard square
can reach the other square that is located on the same horizontal, vertical, and diagonal line. So there
can be at most one queen at each horizontal line, at most one queen at each vertical line, and atmost
one queen at each of the diagonal lines. This problem can be solved by the backtracking technique. The
concept behind backtracking algorithm used to solve this problem is to successively place the queens
in columns. When it is impossible to place a queen in a column, the algorithm backtracks and adjusts a
preceding queen.
Design and implement to find a subset of a given set S = {Sl, S2, . ,Sn} of n positive integers
whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9,
there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem
instance doesn't have a solution.
#include<stdio.h>
//#include<conio.h>
int s[10],d,n,set[10],count=0;
void display(int);
int flag=0;
void main()
{
int subset(int,int);
int i;
//clrscr();
printf("Enter the number of elements in set\n");
scanf("%d",&n);
printf("Enter the set values\n");
for(i=0;i<n;i++)
{
scanf("%d",&s[i]);
}
printf("Enter the sum\n");
scanf("%d",&d);
printf("The progrm output is\n");
subset(0,0);
if(flag==0)
printf("there is no solution");
//getch();
}
int subset(int sum,int i) 44
{
if(sum==d)
{
flag=1;
display(count);
return;
}
if(sum>d||i>=n)
return;
else
{
set[count]=s[i];
count++;
subset(sum+s[i],i+1);
count--;
subset(sum,i+1);
}
}
void display(int count)
{
int i;
printf("{");
for(i=0;i<count;i++)
printf("%d",set[i]);
printf("}");
}
45
CO 5 Implement algorithm to solve problems by branch and bound approach.
Problem 6. Write a program in C/C++ to implement Travelling Sales Person problem. (CO5:
Branch and Bound)
Introduction: Travelling Salesman Problem (TSP): This problem can be defined as : “given n cities
and distance between each pair of cities, find out the path which visits each city exactly once and come
back to starting city, with the constraint of minimizing the travelling distance.”
TSP has many practical applications. It is used in network design, and transportation route design. The
objective is to minimize the distance. We can start tour from any random city and visit other cities in
any order. With n cities, n! different permutations are possible. Exploring all paths using brute force
attacks may not be useful in real life applications.
Branch and bound is an effective way to find better, if not best, solution in quick time by pruning some
of the unnecessary branches of search tree.
It works as follow :
Consider directed weighted graph G = (V, E, W), where node represents cities and weighted
directed edges represents direction and distance between two cities.
46
Program: Travelling Sales Person Problem implementation C
#include<stdio.h>
int a[10][10], visited[10], n, cost = 0;
void get() {
int i, j;
printf("Enter No. of Cities: ");
scanf("%d", &n);
printf("\nEnter Cost Matrix: \n");
for (i = 0; i < n; i++) {
printf("\n Enter Elements of Row# : %d\n", i + 1);
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
visited[i] = 0;
}
printf("\n\nThe cost list is:\n\n");
for (i = 0; i < n; i++) {
printf("\n\n");
for (j = 0; j < n; j++)
printf("\t % d", a[i][j]);
}
}
void mincost(int city) {
int i, ncity;
visited[city] = 1;
printf("%d –>", city + 1);
ncity = least(city);
if (ncity == 999) {
ncity = 0;
printf("%d", ncity + 1);
cost += a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c) {
int i, nc = 999;
int min = 999, kmin;
for (i = 0; i < n; i++) {
if ((a[c][i] != 0) && (visited[i] == 0))
if (a[c][i] < min) {
min = a[i][0] + a[c][i];
kmin = a[c][i];
nc = i;
}
}
if (min != 999) 47
cost += kmin;
return nc;
}
void put() {
printf("\n\nMinimum cost:");
printf("%d", cost);
}
void main() {
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
}
48
Students List
S.
Section AKTU Roll No Name
No.
1 DG1 2100680100181 KASHISH VERMA
2 DG1 2100680100182 KAVYA SANGWAN
3 DG1 2100680100183 KESHAV VASHISTHA
4 DG1 2100680100184 KHUSBU KASHYAP
5 DG1 2100680100185 KHUSHANK GAUTAM BISODIYA
6 DG1 2100680100186 KHUSHI
7 DG1 2100680100187 KHUSHI GUPTA
8 DG1 2100680100188 KHUSHI RASTOGI
9 DG1 2100680100189 KRATI
10 DG1 2100680100190 KRISH TYAGI
11 DG1 2100680100191 KRISHNA PARASHAR
12 DG1 2100680100192 KULDEEP KUMAR
13 DG1 2100680100193 KUNAL AHALAWAT
14 DG1 2100680100194 KUNAL RATHI
15 DG1 2100680100195 KUNAL YADAV
16 DG1 2100680100196 LAEEQ AHMED
17 DG1 2100680100197 LAKSHAY PRATAP SINGH
18 DG1 2100680100198 LAKSHYA TYAGI
19 DG1 2100680100199 LAVI KAUSHIK
20 DG1 2100680100200 MADHAV BATHLA
21 DG1 2100680100202 MADHAVI SINGH
22 DG1 2100680100203 MADHUR TYAGI
23 DG1 2100680100204 MANAV ADHANA
24 DG1 2100680100205 MANEESHA
24 DG1 2100680100206 MANIK TYAGI
26 DG1 2100680100207 MANISH MITTAL
27 DG1 2100680100208 MANPREET KAUR
28 DG1 2100680100209 MANPREET SINGH
29 DG1 2100680100210 MANSI RASTOGI
30 DG1 2100680100211 MASHRUFA MONDAL
31 DG1 2100680100212 MAYANK CHAUHAN
32 DG1 2100680100213 MAYUR VERMA
33 DG1 2100681520008 ANSHIKA SRIVASTAVA
34 DG2 2100680100214 MEENU
35 DG2 2100680100216 MOHD ANAS
36 DG2 2100680100217 MOHD ARSHAN
37 DG2 2100680100218 MODH SAHIL
38 DG2 2100680100219 MOHD SAMEER KHAN
39 DG2 2100680100220 MOHD SHAD
40 DG2 2100680100221 MOHIT SHARMA
49
41 DG2 2100680100222 MUKUL VATS
42 DG2 2100680100223 MUSKAN GAHLOT
43 DG2 2100680100224 NABHANSHU SHARMA
44 DG2 2100680100225 NARENDER SINGH
45 DG2 2100680100227 NIKHIL PANWAR
46 DG2 2100680100228 NISHA RASTOGI
47 DG2 2100680100229 NISHTHA SINGH
48 DG2 2100680100230 NITIN SHARMA
49 DG2 2100680100231 NITISH SHARMA
50 DG2 2100680100232 NITISH SHARMA
51 DG2 2100680100233 PALAK BHARDWAJ
52 DG2 2100680100234 PARTH CHUGH
53 DG2 2100680100235 PARTH GUPTA
54 DG2 2100680100236 PAVITRA PRAKASH
55 DG2 2100680100237 PIYUSH PRATAP SINGH
56 DG2 2100680100238 POOJA PUNYANI
57 DG2 2100680100239 PRAGYA SAINI
58 DG2 2100680100240 PRAGYA SHARMA
59 DG2 2200680109024 TUSHAR DIXIT
60 DG2 2200680109025 VAIBHAV KASHYAP
61 DG2 2200680109026 VANSH SHARMA
62 DG2 2200680109012 MADHUR GUPTA
63 DG2 2200680109013 MANASV KAUSHIK
64 DG2 2200680109015 NIKHIL KUMAR
50
51