0% found this document useful (0 votes)
200 views32 pages

CA-202 - MJP Lab Course - Lab Book Final

The document is a workbook for Second Year Bachelor of Computer Applications (BCA) students at Savitribai Phule Pune University, specifically for the Data Structures Lab Course. It aims to standardize lab assignments across affiliated colleges, providing guidelines for both students and instructors, along with a series of assignments covering various data structure topics. The workbook includes detailed instructions, assessment rubrics, and practical exercises to enhance learning and facilitate continuous assessment.

Uploaded by

shankarasananar8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views32 pages

CA-202 - MJP Lab Course - Lab Book Final

The document is a workbook for Second Year Bachelor of Computer Applications (BCA) students at Savitribai Phule Pune University, specifically for the Data Structures Lab Course. It aims to standardize lab assignments across affiliated colleges, providing guidelines for both students and instructors, along with a series of assignments covering various data structure topics. The workbook includes detailed instructions, assessment rubrics, and practical exercises to enhance learning and facilitate continuous assessment.

Uploaded by

shankarasananar8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Savitribai Phule Pune University

Second Year Bachelor of Computer Applications (BCA)

SEMESTER III

CA-202- MJP Lab Course on

CA201 -MJ Data Structures

Name:

Roll No: Seat No

Academic Year:20 -20


From the Chairman’s Desk
It gives me a great pleasure to present this workbook prepared by the Board of studies in
Computer Applications.

The workbook has been prepared with the objectives of bringing uniformity in implementation
of lab assignments across all affiliated colleges, act as a ready reference for both fast and slow
learners and facilitate continuous assessment using clearly defined rubrics.

The workbook provides, for each of the assignments, the aims, pre-requisites, related
theoretical concepts with suitable examples wherever necessary, guidelines for the faculty/lab
administrator, instructions for the students to perform assignments and a set of exercises
divided into three sets.

I am thankful to the entire team of editors. I am also thankful to the reviewers, Dr. Rahul A.
Patil and Dr. A. B. Nimbalkar. I thank all members of BOS and everyone who have contributed
directly or indirectly for the preparation of the workbook.

Constructive criticism is welcome and to be communicated to the Chairman of the Course and
overall coordinator Dr. Rahul Patil. Affiliated colleges are requested to collect feedbacks from
the students for the further improvements.

I am thankful to Hon. Vice Chancellor of Savitribai Phule Pune University Prof. Dr. Suresh
Gosavi, Pro Vice Chancellor Dr. Parag Kalkar and the Dean of Faculty of Science and
Technology Dr. Pramod Patil for their support and guidance.

Prof. Dr. S.S. Sane


Chairman, BOS in Computer Applications
Savitribai Phule Pune University, Pune
Editors:
Teacher Name College

K.T.H.M. College, Nashik


Smt. Smita J. Ghorpade
K.T.H.M. College, Nashik
Smt. Sucheta P. Borse

Reviewed By:

1. Dr. Rahul Ashokrao Patil


Principal,
Arts and Commerce College, Satpur,
Nashik

2. Dr. A. B. Nimbalkar
Assistant Professor,
Annasaheb Magar College, Hadapsar
Pune
Introduction
1. About the Workbook:
This workbook is intended to be used by S.Y. Bachelor of Computer Applications (BCA)
students for the Data Structures Assignments in Semester–III. This workbook is designed by
considering all the practical concepts / topics mentioned in syllabus.
2. The objectives of this Workbook are:
1) Defining the scope of the course.
2) To bring the uniformity in the practical conduction and implementation in all colleges
affiliated to SPPU.
3) To have continuous assessment of the course and students.
4) Providing ready reference for the students during practical implementation.
5) Provide more options to students so that they can have good practice before facing the
examination.
6) Catering to the demand of slow and fast learners and accordingly providing the
practice assignments to them.
3. How to use this Workbook:
The workbook is divided into seven assignments. Each DS assignment has three SETS. It is
mandatory for students to complete all the SETs in given slot.
4. Instructions to the Students:
Please read the following instructions carefully and follow them.

• Students are expected to carry this workbook every time they come in the lab for
practical.
• Students should prepare for the assignment by reading the relevant material which
is mentioned in ready reference.
• Instructor will specify which problems to solve in the lab during the allotted slot
and student should complete them and get verified by the instructor. However,
student should spend additional hours in Lab and at home to cover all workbook
assignments if needed.
• Students will be assessed for each assignment on a scale from 0 to 5

Not done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
5. Guidelines for Instructors:

• Make sure that students should follow above instructions.


• Explain the assignment and related concepts using white board if required
or by demonstrating the software.
• Evaluate each assignment carried out by a student on a scale of 5 as
specified above by ticking appropriate box.
• The value should also be entered on assignment completion page of the
respective Lab course.

6. Guidelines for Lab administrator:


You have to ensure appropriate hardware and software is made available to each student. The
operating system and software requirements on server side and also client-side areas given
below:
• Server and Client Side-(Operating System) Linux/Windows
• TurboC
• DevC
Table of Contents
Assign. Topics for the Assignments
No
1 Non-Recursive Sorting Techniques
1. Bubble Sort
2. Insertion Sort
2 Recursive Sorting Techniques
1. Quick Sort
2. Merge Sort
3 Searching Techniques
1. Linear search
2. Binary Search
4 Linked List
1. Linked List
2. Singly Circular LinkedList
3. Doubly LinkedList
4. Doubly Circular LinkedList
5 Stack and Queue
1. Static Stack Implementation
2. Dynamic Stack Implementation
3. Static Queue Implementation
4. Dynamic Queue Implementation
6 Binary Search Tree and its Operations
(Dynamic)
7 Graph
1. Adjacency Matrix Representation
2. Adjacency List Representation
3. In-degree and Out-degree
calculation
4. Depth First Search Traversal
5. Breadth First Search Traversal
Assignment Completion Sheet

Assign. Remark Teacher


Topics for the Assignments
No. Signature
1
Non-Recursive Sorting Techniques
2 Recursive Sorting Techniques
3 Searching Techniques
4 Linked list
5 Stack and Queue
6 Binary Search Tree (Dynamic)
7
Graph

This is to certify that Mr. /Ms.__________________________________________has

successfully completed the course work for CA-202- MJP Lab course on CA201 -MJ

Data Structures during the academic year ________________

Instructor H.O.D /Coordinator

Internal Examiner External Examiner


Assignment No: 1 Non-Recursive Sorting Techniques
INTRODUCTION
SORTING
• Sorting is the process of arranging data in a specific order, typically in ascending or descending order, based
on one or more key fields.

Purpose of Sorting:
• Improves efficiency in searching, merging, and report generation.
• Makes data more readable and easier to analyze.
• Essential in databases and applications like telephone directories, student records, etc.

Key Terms :
• List: A collection of records.
• Record: A data structure with multiple fields.
• Key Field: A unique field used to determine the order of records (e.g., name, ID number).
Example: In a telephone directory with fields like Name, Phone Number, Address, and Pincode,
sorting the list alphabetically by Name allows users to quickly search for a person’s contact.

BUBBLE SORT
Introduction
• Bubble Sort is a simple, comparison-based sorting algorithm that repeatedly compares and swaps
adjacent elements if they are in the wrong order. It's called "Bubble" sort because smaller values gradually
"bubble" to the top (front) of the list.

Working Principle:
• Compare each pair of adjacent elements (A[i] and A[i+1]).
• Swap them if they are not in the correct order (ascending or descending).
• Repeat the process for all elements until the entire list is sorted.

Algorithm:
Step1: Start
Step2: Accept ‘n’ numbers in array ‘A’
Step3: set i=0
Step4: if i<n-1 then goto next step else goto step 9
Step4: set j=0
Step5: if j<n-i-1 then goto next step else goto step 8
Step6: if A[j] > A[j+1] then interchange A[j] and A[j+1]
Step7: j=j+1 and goto step 5
Step8: i=i+1 and goto step 4
Step9: Stop
Characteristics:
• Stable: Does not change the relative order of equal elements.
• In-place: Requires no additional space other than the input array.
• Simple: Easy to understand and implement.
• Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse
sorted.
1
• Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
• Auxiliary Space: O(1)
• Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.

Example: Array Elements :7,6,4,3

INSERTION SORT
Introduction
It is a simple and efficient comparison-based sorting algorithm used for small datasets. It builds the final
sorted list one element at a time by inserting each new element into its correct position in the already sorted
part of the array.

Working Principle:
• Start with the second element, compare it with the previous elements.
• Shift all larger elements to the right.
• Insert the current element at its correct position.
• Repeat for all elements in the list.

Algorithm:
Step1: Start
Step2: Accept ‘n’ numbers and store all in array ‘A’
Step3: set i=1
Step4: if i<=n-1 then goto next step else goto step 10
Step5: set Temp=A[i] and j=i-1
Step6: if Temp < A[j] && j>=0 then goto next step else goto step 9
Step7: set A[j+1]=A[j]
Step8: set j=j-1
Step9: set A[j+1]=Temp
Step10: Stop
2
Characteristics:
1) Time Complexity:
• O(n²) in the worst and average case.
• This happens when the list is in reverse order.
2) Auxiliary Space:
• O(1) — It uses only a small, fixed amount of extra memory (in-place sorting).
3) Boundary Cases:
• Takes the most time when the list is sorted in reverse order.
• Takes the least time (O(n)) when the list is already sorted.
4) Algorithm Type:
• Based on the Incremental Approach — builds the sorted list one element at a time.
5) In-Place Sorting:
• Yes, it doesn’t need extra memory to sort.
6) Stable Sort:
• Yes, equal elements stay in the same relative order after sorting.
Example: Array Elements: 54,26,93,17,77,31,44,55,20

SET A:
1) Write a C program to accept n integers from user and sort it in ascending order by using bubble sort.
2) Write a C program to sort an array of n integers in ascending order by using insertion sort algorithm.

SET B:
1) Write a C program to read the data from “studinfo.txt” file which contains student’s information: rollno
and student_name and sort the data on student_name alphabetically using Bubble Sort (use strcmp).
2) Write a C program to read the data from the file “emp.txt” which contains emp_id and emp_age and
sort the data on age in ascending order using insertion Sort.
3
SET C:
1) Write a C program to generate n random nos. using rand () function and store it in an array. Apply
Bubble sort (in descending order) on this array.
2) Write a C program to sort a random array of n integers (using rand () function) by
using Insertion Sort algorithm in descending order.
3) Write a C program to sort the elements by initializing the array (e.g int Arr[5] = {35,66,10,31})
using bubble sort.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge

4
Assignment No: 2 Recursive Sorting Techniques

INTRODUCTION
1. 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.
Key Idea:

• Pick a pivot (we'll choose the first element).


• Partition the array so that:
o Elements less than the pivot go to the left.
o Elements greater than the pivot go to the right.
• Recursively apply this process to the left and right sub-arrays.

Algorithm:
Step 1: start.
Step 2: A is an array of n element.
Step 3:lb=0 //lb = lower bound
ub=n-1 //ub = upper bound.
Step 4: if(lb<ub)
j=partition(A,lb,ub) // j is the pivot position

quicksort(A,lb,j-1);
quicksort(A,j+1,ub);

• Now, we must write the function to partition the array. There are many methods to do the
partitioning depending upon which element is chosen as the pivot.
• We will be selecting the first element as the pivot element and do the partitioning accordingly.
• We shall choose the first element of the sub- array as the pivot and find its correct position in the sub-
array.
• We will be using two variables down and up for moving down and up array.

Algorithm for partitioning


Step 1:down=lb+1
Step 2:up=ub
Step 3:pivot=A[lb]
Step 4: perform step 5 to 7 as long as down<up else go to step 8.
Step 5: while (A[down]<=pivot&&down<ub)
down++;
Step 6: while(A[up]>pivot)
up--;
Step 7: if (down<up) interchange A[down] and A[up]
Step 8: interchange A[up]and pivot,j=up
Step 9: return up
Step 10: stop.
• In this algorithm we want to find the position of pivot i.e.A[lb].
• We use two pointers up and down initialized to the first and last elements respectively.
• We repeatedly increase down as long as the element is < pivot.
• We repeatedly decrease up as long as the element is > pivot.

5
• If up and down cross each other i.e. up<=down, the correct position of the pivot is up and A[up] and
pivot are inter changed.
• If up and down do not cross A[up] and A[down] are interchanged and process is repeated till they do
not cross or coincide.

• Efficiency of quicksort.
Best case = average case = O(nlogn)
Worst case = O(n2)

Example: Array Elements:9,-3,5,2,6,8,-6,1,3

Merge Sort
• Merging is the process of combining two or more sorted data lists into a third list such that it is
also sorted.
• Merge sort follows Divide and Conquer strategy.
- Divide :- Divide the list or array recursively into two halves until it can no more be divided .
- Conquer :- Each subarray is sorted individually using the merge sort algorithm .
- Combine :- The sorted subarrays are merged back together in sorted order. The process
continues until all elements from both subarrays have been merged.
• In this, two lists are compared and the smallest element is stored in the third array.

Algorithm:-
Step 1: Start
Step 2: initially the data is considered as a single array of n element.
Step 3: divide the array into n/2 sub-array each of length 2i (i is 0 for 0th
iteration). i.e. array is divided into n sub-arrays each of 1
element.
Step 4: merge two consecutive pairs of sub-arrays such that the
resulting sub-array is also sorted.
Step 5: The sub-array having no pairs is carried as it is.
Step 6: step 3 and 4 are repeated till there is only one sub-
array remaining of size n.
Step 7: stop.

6
Example: Array Elements: 6,5,12,10,9,1

SET A:
1) Write a program in C to accept 5 numbers from the user and sort the numbers in ascending order by
using Quicksort.
2) Write a C program to sort a random array of n integers by using Quick Sort algorithm in ascending
order.
3) Write a C program to accept and sort n elements in ascending order by using Quicksort.
SET B:
1) Write a program in C to accept 5 numbers from the user and sort the numbers in ascending order by
using Merge sort.
2) Write a C program to sort a random array of n integers by using Merge Sort algorithm in ascending
order.
SET C:
1) Write a C program to sort the elements by initializing the array (e.g. int A[5] = {20,30,44,51,87})
using Merge sort.
2) Write a C program to sort the elements by initializing the array (e.g. int A[5] = {17,12,23,4,8})
using Quick Sort.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge
7
Assignment No: 3 Searching Techniques
INTRODUCTION
1. Linear Search:
• Linear search is one of the most basic search techniques.
• It involves checking each element in a list or array one by one until the desired item is found.
• If a match is located, that item is returned immediately; otherwise, the search goes on until all
elements have been examined.
• Time Complexity of Linear Search is Best Case O (1), Worst case O(n) where n is the number of
elements.

Example 1:
Input arr[] = {15, 25, 45, 90, 35, 60, 75, 120, 30, 55}
Search element x = 75;
Output:
The element is present at 6th index position.
Example 2:
Input: arr[] = {5, 18, 25, 33, 47, 59, 68, 72, 89, 95}
Search element x = 50;
Output:
Element x is not present in arr[].

Algorithm: Linear_Search(arr, n, x)
1. Start
2. Input:
- arr[]: array of elements
- n: number of elements in arr[]
- x: element to search for
3. Repeat for i = 0 to n - 1
a. If arr[i] == x
- Return i (index where x is found)
4. If loop completes and no match is found
- Return -1 (x not found)
5. End

2. Binary Search:
• In binary search, the array must be sorted before start searching process.
• The method starts by comparing the target value with the middle item.
• Based on the comparison, the algorithm eliminates half of the remaining elements and
focuses on the relevant half.
• This continues until the value is found or the subarray becomes empty.
• The search is efficient, with a time complexity of O(log₂ n).

8
Example:

Algorithm: BINARY_SEARCH(arr, n, x)

1. Start
2. Input:
arr[]: a sorted array of 'n' elements
x: the target value to search
3. Initialize:
low = 0
high = n - 1
4. Repeat while low ≤ high:
a. mid = (low + high) / 2
b. If arr[mid] == x:
Return mid (element found)
c. Else if x < arr[mid]:
high = mid - 1 (search in left half)
d. Else:
low = mid + 1 (search in right half)
5. If loop ends, element not found:
Return -1
6. End
SET A:
1) Write a C program to implement linear search on an integer array. Search a given key in an
array.
2) Write a C program that accepts an integer input from the user and search for key element in a
sorted array using binary search.
9
SET B:
1) Write a C program to create an array of strings. Accept student name from user and use linear
search method to check whether the given student’s name is present or not. Display proper message
in output.

2) Write a C program to accept n elements from user store it in an array. Accept a value from the user
and use recursive binary search method to check whether the value is present in array or not.

SET C:
1) Write a C program to read the data from file 'cities.txt' containing names of 10 cities and their STD
codes. Accept a name of the city from user and use linear search algorithm to check whether the
name is present in the file and output the STD code, otherwise output “city not in the list”.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge

10
Assignment No: 4 Linked list

INTRODUCTION
Linked List:
A linked list is a linear data structure. It is collection of items, which are not stored at contiguous memory
locations. The elements in a linked list are connected using pointers.
IMPLEMENTATION OF LINKED LIST
A linked list may be implemented in two ways
1) Static representation
2) Dynamic representation.

1) Static Representation:
An array is used to store the elements of the list. Two arrays are used : first array to store data and
second array to store link.
Index Data Link (Next Index)
-------------------------------------------------
0 Mango 3 → points to index 3
3 Banana 1 → points to index 1
1 Orange 6 → points to index 6
6 Grapes -1 → end of list

2) Dynamic Representation:
• A linked list is a dynamic data structure when a new data is added, the size should increase and
when elements are deleted, its size should decrease.
• To store a list in memory, dynamically memory is allocated for each node and linking them by
means of pointers since each node will be at random memory location. We will need a pointer to
store the address of the first node(head).

Mango Orange Banana Apple NULL

TYPES OF LINKED LIST


• Singly Linkedlist
• Singly Circular Linkedlist
• Doubly Linkedlist
• Doubly Circular Linkedlist
1) Singly Linked list- Each node has two parts: data and next. In ‘data’ we can store any type of data
and ‘next’ is a pointer pointing to nextnode.

Data next

Ex.

10 next 20 next 30 NULL

11
2) Singly Circular Linked list - In this list, the last node points back to the first node i.e. last
node contains the address of the first node.
Singly Circular linked list

Data next Data next Data next

Ex.

Mango Orange Banana Apple

3) Doubly Linked list - Each node in this contains two pointers, one pointing to the previous node
and the other pointing to the next node. This list is used when traversing in both directions is
required.

prev data next

Ex.

4) Doubly Circular Linked list –

In this list, the last node does not contain a NULL pointer but points back to the first node i.e. it
contains the address of the first node.

12
OPERATIONS ON A LIST -The following are some of the basic list operation

1. Insertion
a) Insert at Beginning b) Insert at End c) Insert at Position
• Create a new node. • Traverse to the last • Traverse to the node
• Point its next to the node. before the position.
current head. • Point its next to the new • Insert the new node
• Update head to point to node. between them.
the new node.
Before: Before: Before:
[10] → [20] [10] → [20] [10] → [30]
After: After: After:
[5] → [10] → [20] [10] → [20] → [30] [10] → [20] → [30]

2. Deletion
a) Delete from Beginning b) Delete from End c) Delete by Value/ Position
• Update head to head->next • Traverse to the second- • Find node before the
last node. target.
• Set its next to NULL. • Change its next to skip
the target node.
Before: Before: Before:
[10] → [20] [10] → [20] [10] → [30]
After: After: After:
[20] [10] [10] → [20] → [30]

3. Traversal
• Start at the head.
• Move node by node using the next pointer.
• Display or process data at each node.

4. Search
• Traverse the list.
• Compare each node's data with the target.
• Return position or address if found.

Search for 20:


[10] → [20] → [30]

Match!

5. Count Nodes / Length


• Similar to traversal.
• Use a counter and increment at each node.

13
6. Reverse the Linked List
• Re-point the next pointers in reverse.
• Use three pointers: prev, current, next.
Before: Head → [10] → [20] → [30] → NULL
After: Head → [30] → [20] → [10] → NULL

7. Sort the List


• Use basic sorting algorithms (Bubble, Insertion).
• Compare node data and swap.

SET A
1) Write a C program to implement a Singly linked list with following operations:
create() , display(), insert(),delete()
2) Write a C program to implement a Singly Circular linked list with following operations:
create(), display(), search(),length()
3) Write a C program to implement a Doubly linked list with create(),display(),insert(),delete()
operation.

SET B
1) Write a C program to implement a Doubly Circular linked list with following operations
create() and display()
2) Write a C program to implement a Doubly Circular linked list with following operations
create() and display(), append(),delete()

SET C
1) Write a C program to concatenate two LinkedList.
2) Write a C program to find intersection of two LinkedList.
3) Write a C program to reverse a singly LinkedList.

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge

14
Assignment No: 5 Stack and Queue
INTRODUCTION

1. Stack:
o A stack is an ordered collection of items into which items may be inserted and deleted from one
end called the top of the stack.
o The stack is a linear data structure which operates in a LIFO (last in first out) manner. i.e. the
element which is put in last is the first to come out. That means it is possible to remove elements
from stack in reverse order.
o Real life Examples: stack of coins, stack of dishes etc. only the topmost plate can be taken and
any new plates has to be put at the top.

PRIMITIVE OPERATIONS ON A STACK:


o Create o Isempty
o Push o Isfull
o Pop o Peek

Stack can be implemented in two ways: static implementation and dynamic implementation

a. Static Implementation:
o A stack can be statically implemented using an array with a fixed size, often defined by a
constant MAX.
o The variable top is used to keep track of the index of the topmost element.
o The stack structure consists of both the array to store elements and the top variable.
o Elements stored in the stack may include integers, characters, strings, or even
user-defined data types.
Operations on Static Stack:
Operation Description Syntax / Time
Function Complexity
Push Adds an element to the top of the push(element) O(1)
stack
Pop Removes the top element from the element=pop() O(1)
stack
Peek / Top Returns the top element without peek() or top() O(1)
removing it
isEmpty Checks whether the stack is empty isEmpty() O(1)
isFull (In static stacks) Checks whether the isFull() O(1)
stack is full
Size Returns the number of elements size() O(1)
currently in the stack
Display Prints all elements in the stack from display() O(n)
top to bottom
Clear Removes all elements from the stack clear() O(1) or
O(n)*
b. Dynamic Implementation:
o In a dynamic implementation, a stack is created using a linked list, where every node includes
a data value and a link to the next node.
o The stack is maintained using a pointer to the top node, and all operations are performed
relative to this pointer.
o Elements in the stack can be of any data type, including user-defined types.
o This linked-list-based stack has the advantage of being flexible in size, growing and shrinking
as needed during runtime.
15
Operations on Dynamic Stack:

Operation Description Syntax Time


Complexity
Push(x) Inserts an element x at the top of the stack top = push(top, x); O(1)

Pop() Removes the top element from the stack top = pop(top); O(1)

Peek() Returns the top element without removing it peek(top); O(1)

isEmpty() Checks if the stack is empty if (top == NULL) O(1)

Display() Prints all elements from top to bottom display(top); O(n)

Clear() Removes all elements and deallocates memory clearStack(top); O(n)


top = NULL;

2. Queue:
o A queue is a type of linear data structure that organizes elements in a specific sequence for
processing.
o It follows the First In, First Out (FIFO) or sometimes described as Last In, Last Out (LILO) principle,
meaning that the element inserted first is removed first.
o In a queue, items are inserted at the rear and removed from the front. Queues can be implemented statically
using arrays or dynamically using linked lists.

PRIMITIVE OPERATIONS ON A QUEUE:


o Create o Isempty
o Add o Isfull
o Delete o Front/Peek

Queue can be implemented in two ways: static implementation and dynamic implementation

a. Static Implementation of Queue:


o A queue implemented statically uses a fixed-size array (of size MAX) to store elements,
along with two integer variables, front and rear, which indicate the positions of the first
and last elements, respectively.
o The queue as a whole comprises the array and these two position trackers.
o Elements enter the queue at the rear end and exit from the front end.
o The queue can accommodate different types of data, including integers, characters, strings,
or custom types.

16
Operations on Static Queue:

Operation Description Syntax / Function Time


Complexity

init() Initialize a queue i.e. front=rear= -1 init() O(1)

add(x) Adds element x to the rear of the queue add(x) O(1)

delete() Removes and returns element from the front of the delete() O(1)
queue

Peek / Returns the element at the front without removing it peek() or front() O(1)
Front()

isEmpty() Checks whether the queue is empty isEmpty() O(1)

isFull() Checks if the queue is full (only for fixed-size array isFull() O(1)
implementation)

Display() Prints all the elements in the queue from front to rear display() O(n)

Size() Returns the number of elements currently in the size() O(1)


queue

b. Dynamic Implementation of Queue:


o A queue can be implemented dynamically using a linked list where each node consists of two parts:
the data and a pointer to the next node.
o Typically, to represent a queue as a single entity, two pointers are required—one for the front and
one for the rear.
o To simplify this, a circular linked list is used where only one pointer is maintained, which points to
the rear node.
o The front of the queue can be accessed easily as the node following the rear.
o The queue can store data types like integers, characters, strings, or user-defined types, and it can
grow without any fixed size limitation.

17
Operations on Dynamic Queue:
Operation Description Syntax / Time
Function Complexity

init() Create an empty queue as a circular linked list by init() O(1)


initializing Q to NULL indicating that the queue is
empty

add(x) Adding an element x tso the queue Q requires add (Q, x) O(1)
creation of node containing x and putting it next to
the rear and rear points to the newly added element.
This changes the rear pointer Q and the function
should return the changed value of Q.

delete () Deletes the front node from the queue Q which is X=delete (Q) O(1)
actually next element to the rear pointer Q.
However, if queue contains only one element, (Q-
>next == Q) then deleting this single element can be
achieved by making empty Q (Q =NULL). Since the
rear pointer Q is changed in this case, function
should return the changed value of Q. The function
call will be as follows:
Q=delete(Q);

Peek / returns the data element in the front (Q->next) node X=peek (Q) O(1)
Front() of the Queue Q

isEmpty () Check if the Queue is empty which is equivalent to isEmpty (Q) O(1)
checking if Q==NULL

isFull() Checks whether the queue is full. Queue becomes isFull(Q) O(1)
full when front reaches to MAX -1.

Display () Prints all the elements in the queue from front to rear display(Q) O(n)

Size () Returns the number of elements currently in the size(Q) O(1)


queue

18
SET A:
1) Write a C program to perform Static implementation of Stack on integers data with
following operation:
Initialize (), push (), pop (), isempty (), isfull()

2) Write a C program to perform Dynamic implementation of Stack on character data with


following operation:
Initialize(), push(), pop(), display(), peek()

SET B:
1) Write a C program to perform Static implementation of Queue on integers data with
following operation:
Initialize(), insert(), delete(), isempty(), display()

2) Write a C program to perform Dynamic implementation of Queue on character data with


following operation:
Initialize(), insert(), delete(), isempty(), display(), peek()

SET C:
1) Write a C program to reverse the stack by using recursive function.
2) Write a C program to convert infix expression to postfix expression
3) Write a C program to perform Static implementation of circular queue of integers with
following operation:
Initialize(), insert(), delete()

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge

19
Assignment No: 6 Binary Search Tree (Dynamic)

INTRODUCTION
Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties-
• The value of the key of the left sub-tree is less than the value of its parent (root) node's key.
• The value of the key of the right sub-tree is greater than or equal to the value of its parent
(root) node's key.
• The left and right sub tree each must also be a binary search tree.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and can be
defined as – left_subtree (keys) < node (key) ≤ right_subtree (keys)

Basic Operations
Following are the basic operations of a tree –
• init (T) – creates an empty Binary search tree by initializing T to NULL
• Search(T,x) − Searches an x element in a tree.
• Insert(T,x) − Inserts an element in a tree.
• Pre-order Traversal (Root, Left, Right)− Traverses a tree in a pre-order manner.
• In-order Traversal (Left, Root, Right) − Traverses a tree in an in-order manner.
• Post-order Traversal (Left, Right, Root) − Traverses a tree in a post-order manner.

20
Representation of Binary Search Tree

1. Static Representation of Binary Tree:


o One way to represent a binary tree is by storing its nodes in an array, arranged level by level, starting
from the root at level zero.
o This method involves assigning sequential indices to the nodes, starting from the root, then moving
through each level of the tree.
o In the case of a complete binary tree of height h, the total number of nodes is given by the formula
2^(h+1) − 1.
o The tree can be stored in a one-dimensional array called TREE, where each node is placed at index
TREE(i).
o Therefore, the array should have a size of 2^(h+1) − 1, or 2^d − 1 where d is the number of levels.

2. Linked Representation of Binary Tree:


o A binary search tree can also be represented using a linked list, which is often more memory-efficient
than array-based representations.
o In this approach, all nodes are created dynamically in memory.
o Each node contains three fields: one for the data, one for the left child (Lchild), and one for the
right child (Rchild). The root pointer serves as the entry point to the tree structure in memory.

Consider the structure of a node of a BST:


typedef struct BST
{
struct BST * Lchild;
int data;
struct BST * Rchild;
}BSTnode;

21
1. Algorithm INSERT_BST(root, value):

1. If root is NULL:
a. Create a new node
b. Assign value to its data field
c. Set left and right child to NULL
d. Return the new node
2. Else If value < root.data:
a. root.left = INSERT_BST(root.left, value)

3. Else If value > root.data:


a. root.right = INSERT_BST(root.right, value)

4. Return root

2. Algorithm SEARCH_BST(root, key):

1. If root is NULL:
Return "Element not found"

2. If key == root.data:
Return "Element found"

3. If key < root.data:


Return SEARCH_BST(root.left, key)

4. Else:
Return SEARCH_BST(root.right, key)
SET A
1) Write C programs to create and display the elements using Inorder, Preorder and Postorder traversal.
2) Write a C program to implement binary search tree of integers with following operations:
insert () a new element, count_nonleaf (), count_leaf (), count_total_nodes ()

SET B
1) Write a C program to implement binary search tree of integers with following operations:
tcopy (): tree copy, tcompare (): comparison of two trees,
2) Write a C program to implement binary search tree of integers with following operations:
search (): search an element from tree, mirror () : find mirror image of a tree

SET C
1) Write a C program to create binary search tree and delete specific node from a tree.

Assignment Evaluation

0: Not Done[] 1: Incomplete[ ] 2: Late Complete []

3: Needs Improvement[ ] 4: Complete[] 5: Well Done []

Practical In-charge
22
Assignment No: 7 Graph

INTRODUCTION
• A graph is a non-linear data structure G = (V, E) where:
V is a finite set of vertices (or nodes), and
E is a finite set of edges, representing a pair of vertices that are connected.
Each edge in a graph connects a pair of vertices and can be either:
o Directed: If the edge has a direction (from one vertex to another).
o Undirected: If the edge has no direction (bi-directional connection).
• Mainly there are two types of graphs
o Undirected Graph
o Directed Graph
• An undirected graph represented as G = (V,E) where each edge E is an unordered pair of vertices.
Thus, pairs (v1,v2) and (v2,v1) represent the same edge.
• A directed graph is one, where each edge is represented by a specific direction or by directed pairs
<v1, v2>, where v1 is a tail and v2 is the head of the edge. Hence <v1, v2> and <v2, v1> represent
two different edge.
• To store a graph in memory, it must be represented in a suitable format. The representation affects the
efficiency of graph operations like traversal, searching, and updating. There are two main methods
represent graphs:
o Adjacency Matrix
o Adjacency List
• Adjacency Matrix: Graphs can be represented using an adjacency matrix, which is a 2D array of
dimensions V × V, where V is the number of vertices in the graph.
• Example of Adjacency Matrix

• Adjacency List: An adjacency list stores a list of neighbours for each vertex. It’s usually implemented
using:
o An array of linked lists or arrays.
o Each index corresponds to a vertex, and stores the list of adjacent vertices.

• Example: Adjacency list for Directed weighted graph is shown below:

23
• Operations on Graph: Graphs are powerful and flexible data structures, and a wide range of operations
like find indegree, outdegree, display graph, travels graph-DFS, BFS etc. These operations are essential for
solving problems like pathfinding, cycle detection, network analysis, and more.
o Indegree(i) – returns the indegree (the number of edges ending on) of the ith vertex
o Outdegree(i) – returns the outdegree (the number of edges moving out) of the ith vertex)
o displayAdjMatrix – displays the adjacency matrix for the graph
Graph Traversal Techniques:
Graph traversal is the process of visiting all the nodes (or vertices) of a graph in a systematic manner. It
helps in solving problems like searching, pathfinding, cycle detection, connectivity check, etc.
There are two primary traversal techniques used in graphs:
a) Depth First Search (DFS)
b) Breadth First Search (BFS)

Algorithm: Depth First Search


Note: The graph is represented using an adjacency list or adjacency matrix.
A visited[] array (or set) is used to keep track of the visited vertices.
Time Complexity : O(V+E)

Algorithm DFS(Graph, start_vertex):


1. Mark start_vertex as visited
2. Print start_vertex (or process it)
3. For each neighbor of start_vertex:
a. If neighbor is not visited:
i. Recursively call DFS(Graph, neighbor)

Algorithm: Breadth First Search


Note :
The graph is represented using an adjacency list or adjacency matrix.
A visited[] array or set is used to avoid revisiting vertices.
A queue is used to hold vertices to visit next.
Time Complexity : O(V+E)
24
Algorithm BFS(Graph, start_vertex):
1. Create a queue Q
2. Mark start_vertex as visited
3. Enqueue start_vertex into Q
4. While Q is not empty:
a. Dequeue a vertex from Q and call it current_vertex
b. Process (print/use) current_vertex
c. For each neighbor of current_vertex:
i. If neighbor is not visited:
- Mark neighbor as visited
- Enqueue neighbor into Q
SET A:

1) Write a C program that accepts the vertices and edges for a graph and stores it as an adjacency matrix.
Implement functions to print indegree, outdegree and to display the adjacency matrix.
2) Write a C program that accepts a graph and stores it as an adjacency list. Implement functions to print
outdegree of any vertex i.

SET B:
1) Write a C program to read a graph as adjacency matrix and Traverse using DFS
2) Write a C program to read a graph as adjacency matrix and Traverse using BFS

SET C:

1) Write a C program to read an undirected graph as adjacency matrix and find if it contains a cycle.

2) Write a C program that accepts the graph and check if graph fully connected or not?

Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Practical In-charge

25

You might also like