You are on page 1of 15

DR B.R.

AMBEDKAR NATIONAL INSTITUTE OF


TECHNOLOGY JALANDHAR, PUNJAB-144011

Department of Computer Science and Engineering

Laboratory Manual
Design and Analysis of Algorithms Lab
(CSPC-226)

Prepared during (Jan-Jun 2024) By:


Name: Kushal Vithal
Roll No: 22103091
Dr B R Ambedkar National Institute of Technology, Jalandhar
CSPC-226 Design and Analysis of Algorithms Lab
B.TECH (CSE) 4th Semester

Vision of the Department


To be recognized globally for imparting computer science education and research of high
distinction, both of value and relevance to society

Mission of the Department


M1: To impart contemporary knowledge and skill relevant to the field of Computer Science
and Engineering to maximize employability and potential.
M2: To strengthen multifaceted competence in the different core and allied areas of Computer
Science in order to nurture creativity, innovations and out-of-the-box thinking.
M3: To promote research and expertise in Computer Science and Engineering in order to serve
the needs of Industry, Government and Society and motivate the students for lifelong learning.
M4: To inculcate professional ethics and social values through co-curricular and
extra–curricular activities for holistic nation building.

Program Educational Objectives (PEOs)


• To create and sustain a community of learning in which students acquire knowledge
and apply in their concerned fields with due consideration for ethical, ecological, and
economic issues.
• To provide knowledge based services so as to meet the ever-changing needs of industry
and society at large.
• To make the students understand, design and implement the concepts in multiple arenas.
• To foster holistic growth of students that would provide ample E 2 opportunities.

Program Outcomes (POs)


i) Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
ii) Problem Analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences.
iii) 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.
iv) 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 for complex problems.

2
v) Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
vi) 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.
vii) 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.
viii) Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
ix) Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
x) 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.
xi) 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.
xii) Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and lifelong learning in the broadest context of technological
change.

Program Specific Outcomes (PSOs)

PSO1: Analyse, design, develop, evaluate and apply mathematical basics, data structures and
algorithms for modelling computer hardware/software to solve real-world and interdisciplinary
research problems.
PSO2: Demonstrate contemporary technologies, data analysis and computing skills for
effective interpretation and decision-making in the sustainable development of the society.

3
Dr B R Ambedkar National Institute of Technology, Jalandhar
CSPC-226 Design and Analysis of Algorithms Lab
B.TECH (CSE) 4th Semester

Syllabus with COs-POs Mapping

DEPARTMENT: COMPUTER SCIENCE AND ENGINEERING


COURSE CODE: CSPC-226
COURSE TITLE: DESIGN AND ANALYSIS OF ALGORITHMS
LABORATORY
COURSE DESIGNATION: REQUIRED
PRE-REQUISITES: NONE
CONTACT HOURS/CREDIT SCHEME: (L-T-P-C: 0-0-2-1)
COURSE ASSESSMENT METHODS: Assignments for each topic to be evaluated
in the lab, and final evaluation at the end which includes Viva Voce, Conduct of the
experiment

COURSE OUTCOMES
After the course completion, the student will be able to:
1. Learn how to analyze algorithms and estimate their worst case and average-case behavior.
2. Analyze fundamental data structures with the manner in which these data structures can be
implemented.
3. Applying algorithm design strategies, sorting and searching techniques and solution of
relevant recurrence relations to real life applications.
4. Design and implement optimization algorithms in specific applications.

LIST OF PRACTICALS
1. Program to implement Quick sort using the Divide and Conquer technique and analyze its
Time Complexity.
2. Program to implement Merge sort using the Divide and Conquer technique and analyze its
Time Complexity.
3. Program to perform Binary Search using the Divide and Conquer technique and analyze its
Time Complexity.

4
4. Program to implement Starssen’s Matrix Multiplication Algorithm and analyze its Time
Complexity.
5. Program to find the Minimum Spanning tree using prim’s algorithm.
6. Program to find the Minimum Spanning tree using kruskal’s algorithm.
7. Program to solve the knapsack problem using greedy method.
8. Program to find the shortest path of the multistage graph using dynamic programming.
9. Program to solve the Traveling salesman problem using the dynamic programming
approach.
10. Program to solve the Optimal Binary Search Tee problem using the dynamic
programming approach.
11. Program to find the solution to the N queen’s problem using backtracking.
12. Program to find the shortest path using Floyd’s algorithm.
13. Program to solve Graph Coloring problem.
14. Program to solve Hamiltonian Cycle Problem.
15. Program to implement Knuth Morris Pratt algorithm and analyze its time complexity.

5
INDEX

S.no Title Page Date Signature


No.

6
7
Week 1

Program1: Program to perform Binary Search using the Divide and Conquer technique
and analyze its Time Complexity.

Description:
Binary search is the search technique that works efficiently on sorted lists. Hence, to search an
element into some list using the binary search technique, we must ensure that the list is sorted.

Binary search follows the divide and conquer approach in which the list is divided into two
halves, and the item is compared with the middle element of the list. If the match is found
then, the location of the middle element is returned. Otherwise, we search into either of the
halves depending upon the result produced through the match.

ALGORITHM:

• Divide the search space into two halves by finding the middle index “mid”.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be used as the next
search space.
o If the key is smaller than the middle element, then the left side is used for
next search.
o If the key is larger than the middle element, then the right side is used for
next search.
• This process is continued until the key is found or the total search space is
exhausted.

Time Complexity of Binary Search:


• Best Case Complexity - In Binary search, best case occurs when the element to search
is found in first comparison, i.e., when the first middle element itself is the element to
be searched. The best-case time complexity of Binary search is O(1).
• Average Case Complexity - The average case time complexity of Binary search
is O(logn).
• Worst Case Complexity - In Binary search, the worst case occurs, when we have to
keep reducing the search space till it has only one element. The worst-case time
complexity of Binary search is O(logn).

Explanation:
• During the first iteration, the element is searched in the entire array. Therefore, length
of the array = n.
• In the second iteration, only half of the original array is searched. Hence, length of the
array = n/2.
• In the third iteration, half of the previous sub-array is searched. Here, length of the
array will be = n/4.
8
• Similarly, in the ith iteration, the length of the array will become n/2i

To achieve a successful search, after the last iteration the length of array must be 1.
So n/2i = 1
That gives us −
n = 2i
Applying log on both sides,
log n = log 2i
log n = i. log 2
i = log n
The time complexity of the binary search algorithm is O(log n)

9
SOURCE CODE:

#include<bits/stdc++.h>
using namespace std;

int binary_search(int arr[],int n,int key){


sort(arr,arr+n);
int s=0;
int e=n-1;
int ans=-1;
int mid;
while(s<=e){
mid= s+ (e-s)/2;
if(arr[mid]==key){
ans=mid;
break;
}
else if(arr[mid]<key){
s=mid+1;
}else{
e=mid-1;
}
}
return ans;
}

int main(){
cout<<"Enter the number of Elements in array: ";
int n;
cin>>n;
int arr[n];
cout<<"Enter the elements:"<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
int key;
cout<<"Enter the Element to search: ";
cin>>key;
cout<<"Key is present at index: "<<binary_search(arr,n,key);

return 0;
}

10
OUTPUT:

11
Program 2: Program to implement Quick sort using the Divide and Conquer technique
and analyze its Time Complexity.

Description:
Quicksort picks an element as pivot, and then it partitions the given array around the picked pivot
element. In quick sort, a large array is divided into two arrays in which one holds values that are
smaller than the specified value (Pivot), and another array holds the values that are greater than the
pivot.

After that, left and right sub-arrays are also partitioned using the same approach. It will
continue until the single element remains in the sub-array.

Divide: In Divide, first pick a pivot element. After that, partition or rearrange the array into
two sub-arrays such that each element in the left sub-array is less than or equal to the pivot
element and each element in the right sub-array is larger than the pivot element.

Conquer: Recursively, sort two subarrays with Quicksort.

Combine: Combine the already sorted array.

ALGORITHM:

Quick Sort Algorithm:


Step 1: Make the right-most index value pivot.
Step 2: partition the array using the pivot value.
Step 3: quicksort left partition recursively.
Step 4: quicksort right partition recursively.

Quick Sort Pivot Algorithm:


Step 1: Choose the highest index value that has a pivot.
Step 2: Take two variables to points left and right of the list excluding the pivot.
Step 3: left points to the low index.
Step 4: right points to the high.
Step 5: While the value at left is less than the pivot move right.
Step 6: While the value at the right is greater than the pivot move left.
Step 7: if both Step 5 and Step 6 do not match swap left and right.
Step 8: if left ≥ right, the point where they met is the new pivot.

Time Complexity of Quick Sort:

• Best Case Complexity - In Quicksort, the best-case occurs when the pivot element is
the middle element or near to the middle element. The best-case time complexity of
quicksort is O(n*logn).
• Average Case Complexity - It occurs when the array elements are in jumbled order
that is not properly ascending and not properly descending. The average case time
complexity of quicksort is O(n*logn).
• Worst Case Complexity - In quick sort, worst case occurs when the pivot element is
either greatest or smallest element. Suppose, if the pivot element is always the last
element of the array, the worst case would occur when the given array is sorted

12
already in ascending or descending order. The worst-case time complexity of
quicksort is O(n2).
Explanation:
T(K): Time complexity of quicksort of K elements
P(K): Time complexity for finding the position of pivot among K elements.
BEST CASE:
The best case occurs when we select the pivot as the mean. So here
T(N) = 2 * T(N / 2) + N * constant
Now T(N/2) is also 2*T(N / 4) + N / 2 * constant. So,
T(N) = 2*(2*T(N / 4) + N / 2 * constant) + N * constant
= 4 * T(N / 4) + 2 * constant * N.
So, we can say that
T(N) = 2k * T(N / 2k) + k * constant * N
then, 2k = N
k = log2 N
So T(N) = N * T(1) + N * log2 N. Therefore, the time complexity is O(N * logN).
WORST CASE:
The worst case will occur when the array gets divided into two parts, one part consisting of
N-1 elements and the other and so on. So,
T(N) = T(N – 1) + N * constant
= T(N – 2) + (N – 1) * constant + N * constant = T(N – 2) + 2 * N * constant – constant
= T(N – 3) + 3 * N * constant – 2 * constant – constant
...
= T(N – k) + k * N * constant – (k – 1) * constant – . . . – 2*constant – constant
= T(N – k) + k * N * constant – constant * (k*(k – 1))/2
If we put k = N in the above equation, then
T(N) = T(0) + N * N * constant – constant * (N * (N-1)/2)
= N2 – N*(N-1)/2
= N2 /2 + N/2

13
SOURCE CODE:

#include<bits/stdc++.h>
using namespace std;

int partition(int arr[],int low,int high){


int pivot = arr[low];
int i = low;
int j = high;

while (i < j) {
while (arr[i] <= pivot && i <= high - 1) {
i++;
}

while (arr[j] > pivot && j >= low + 1) {


j--;
}
if (i < j) swap(arr[i], arr[j]);
}
swap(arr[low], arr[j]);
return j;
}

void quick_sort(int arr[],int low,int high){


if (low < high) {
int pIndex = partition(arr, low, high);
quick_sort(arr, low, pIndex - 1);
quick_sort(arr, pIndex + 1, high);
}
}

int main(){
int n;
cout<<"Enter the number of Elements in Array: ";
cin>>n;
int arr[n];
cout<<"Enter the Elements in Array: "<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
quick_sort(arr,0,n-1);
cout<<"Sorted Array:"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}

14
OUTPUT:

15

You might also like