LABORATORY MANUAL_DS_CI
LABORATORY MANUAL_DS_CI
LABORATORY MANUAL
DATA STRUCTURE
(CSIT 303)
DEPARTMENT OF
COMPUTER SCIENCE AND INFORMATION
TECHNOLGY
CERTIFICATE
Signature of
Faculty In-charge
INDEX
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.
Theory:
Techniques for searching an ordered list in which we first check the middle item and - based
on that comparison - "discard" half the data. The same procedure is then applied to the
remaining half until a match is found or there are no more items left.
A binary search halves the number of items to check with each iteration, so locating an item
(or determining its absence) takes logarithmic time. A binary search is a divide and conquer
search algorithm.
Algorithm of binary search
int binary_search(int A[], int key, int imin, int imax)
{
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;
else
{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);
// three-way comparison
if (A[imid] > key)
// key is in lower subset
return binary_search(A, key, imin, imid-1);
else if (A[imid] < key)
// key is in upper subset
return binary_search(A, key, imid+1, imax);
else
// key has been found
return imid;}
}
Viva Questions:
Ex. No. - 2. Write a program to perform the following operation in Matrix: 1. Addition
2. Subtraction 3. Multiplication 4. Transpose
Theory:
Algorithm for Matrix Addition
The addition of two matrices A m*n and Bm*n gives a matrix Cm*n. The elements of C are sum
of corresponding elements in A and B which can be shown as:
for i in 1 to m
for j in 1 to n
cij = aij + bij
Key points:
Addition of matrices is commutative which means A+B = B+A
Addition of matrices is associative which means A+(B+C) = (A+B)+C
The order of matrices A, B and A+B is always same
If order of A and B is different, A+B can’t be computed
The complexity of addition operation is O(m*n) where m*n is order of matrices
for i in 1 to m
for j in 1 to n
cij = aij-bij
Key points:
Subtraction of matrices is non-commutative which means A-B ≠ B-A
Subtraction of matrices is non-associative which means A-(B-C) ≠ (A-B)-C
The order of matrices A, B and A-B is always same
If order of A and B is different, A-B can’t be computed
The complexity of subtraction operation is O(m*n) where m*n is order of matrices
Theory:
Matrix multiplication falls into two general categories:
Scalar in which a single number is multiplied with every entry of a matrix
Multiplication of an entire matrix by another entire matrix will refer to second cate-
gory.
In the scalar variety, every entry is multiplied by a number, called a scalar.
Matrix C and D below cannot be multiplied together because the number of columns in
C does not equal the number of rows in D. In this case, the multiplication of these two
matrices is not defined
Viva Questions:
Ex. No. – 3. Write a program to perform the following operation on strings using string
functions: 1. Addition 2. Copying 3. Reverse 4. Length of String
Theory: Strings are used for storing text/characters. For example, "Hello World" is a
string of characters. Unlike many other programming languages, C does not have
a String type to easily create string variables. Instead, you must use the char type and
create an array of characters to make a string in C:
Viva Questions:
1. Explain string in c.
2. Explain Addition of strings.
3. Explain the Concept of copy of string.
4. Explain the Concept of reverse of string.
Ex No. 4. Write program for implementing the following sorting methods to arrange a
list of integers in ascending order: a) Quick sort b) Selection sort c) Insertion sort d)
Merge sort
Aim: To understand the concept of quick sort, Selection sort, insertion sort and
merge sort on a list of integers.
Theory:
Insertion sort is an example of an incremental algorithm; it builds the sorted sequence one
number at a time. This is perhaps the simplest example of the incremental insertion
technique, where we build up a complicated structure on n items by first building it on n − 1
items and then making the necessary changes to fix things in adding the last item. The given
sequences are typically stored in arrays. We also refer the numbers as keys. Along with each
key may be additional information, known as satellite data. [Note that "satellite data" does
not necessarily come from satellite!].Since multiple keys with the same value are placed in
the sorted array in the same order that they appear in the input array, Insertion sort is stable.
This algorithm does not require extra memory.
For Insertion sort we say the worst-case running time is θ(n2), and the best-case running time
is θ(n).
Insertion sort use no extra memory it sort in place.
The time of Insertion sort is depends on the original order of an input. It takes a time in Ω(n2)
in the worst-case, despite the fact that a time in order of n is sufficient to solve large instances
in which the items are already sorted.
Algorithm of insertion sort
INSERTION_SORT (A)
FOR j ← 2 TO length[A]
DO key ← A[j]
{Put A[j] into the sorted sequence A[1 . . j − 1]}
i←j−1
WHILE i > 0 and A[i] > key
DO A[i +1] ← A[i]
i←i−1
A[i + 1] ← key
Theory:
Selection sort is not difficult to analyze compared to other sorting algorithms since none of
the loops depend on the data in the array. Selecting the lowest element requires scanning all n
elements (this takes n − 1 comparisons) and then swapping it into the first position. Finding
progression). Each of these scans requires one swap for n − 1 elements (the final element is
already in place).
if(a[j]>large)
BEGIN
large = a[j];
ind = j;
END IF
END-FOR
a[ind] = a[i];
a[i] = large;
END-FOR
End
Theory:
Quicksort is a sorting algorithm based on the divide and conquer approach where
An array is divided into subarrays by selecting a pivot element (element selected from the
array).While dividing the array, the pivot element should be positioned in such a way that
elements less than pivot are kept on the left side and elements greater than pivot are on the
right side of the pivot. The left and right subarrays are also divided using the same approach.
This process continues until each subarray contains a single element.
At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.
Time complexity of quick sort for best case and average case is O(n*log n) in worst case
O(n2).
Time complexity of merge sort for best case, average case, worst case is O(n*log n) .
Algorithm of Merge Sort
Viva Questions:
1. What is the running time Complexities of insertion sort, quick sort , selection sort, merge
sort in best case?
2. What is the running time Complexity of insertion sort, quick sort , selection sort, merge
sort in worst case?
3. What is the running time Complexity of insertion sort, quick sort , selection sort, merge
sort in average case?
4. Write down the algorithm of insertion sort, quick sort , selection sort, merge sort
5. Write down the advantages & disadvantage of insertion sort, quick sort , selection sort,
merge sort.
Ex. No. 5. Write a program that uses stack operations to convert a given infix
expression into its postfix equivalent.
POSTFIX: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator after (post) its two operands. Example: A B +
Algorithm:
1.Scan the infix expression from left to right.
2.If the scanned character is an operand, put it in the postfix expression.
3.Otherwise, do the following
3.1 If the precedence and associativity of the scanned operator are greater than the
precedence and associativity of the operator in the stack [or the stack is empty or the stack
contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is right associative and other
operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
3.1.1Check especially for a condition when the operator at the top of the stack and the
scanned operator both are ‘^‘. In this condition, the precedence of the scanned operator is
higher due to its right associativity. So it will be pushed into the operator stack.
3.1.2In all the other cases when the top of the operator stack is the same as the scanned
operator, then pop the operator from the stack because of left associativity due to which the
scanned operator has less precedence.
3.2 Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator.
3.2.1 After doing that Push the scanned operator to the stack. (If you encounter parenthesis
while popping then stop there and push the scanned operator in the stack.)
4.If the scanned character is a ‘(‘, push it to the stack.
5.If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6.Repeat steps 2-5 until the infix expression is scanned.
7.Once the scanning is over, Pop the stack and add the operators in the postfix expression
until it is not empty.
8.Finally, print the postfix expression.
Viva questions:
1. What is Infix expression ?
2. What is Postfix expression?
3. What is operator and operands?
4. Rules of conversion infix into postfix?
5. Which operator has highest, lowest precedence?
Ex. No. 6. Write a program to merge two sorted array into one sorted array.
Aim: To understand the concept of Merging two sorted array into one sorted array.
Theory:
An array is a collection of items of same data type stored at contiguous memory locations.
Merging the two sorted array first need two arrays which is already sorted combine them in
third array and apply any sort algorithm.
Algorithm:
1. start the program
2. input the length of both the arrays.
3. Input the arrays elements from user.
4. Copy the elements of the first array to the merged array when initializing it.
5. Copy the elements of the second array to the merged array while initializing the
second array.
6. Sort the merged array now.
7. Display the merged array.
8. The program ends here.
Viva questions:
1. What is array ?
2. What is sorting?
3. What is merging?
4. How to declare arrays?
Aim: To understand the concept of stack and learn the implementation of stack using
array and linked list.
Theory:
A stack is a container of objects that are inserted and removed according to the last-in first-
out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the
item into the stack, and pop the item out of the stack. A stack is a limited access data
structure - elements can be added and removed from the stack only at the top. Push adds
an item to the top of the stack, pop removes the item from the top. A helpful analogy is to
think of a stack of books; you can remove only the top book, also you can add a new book
on the top.
Viva Questions:-
1. What is a stack?
2. What is array?
3. What is linked list?
4. What are the applications of stack?
5. Explain push algorithm of stack?
6. Explain pop algorithm of stack?
7. Why stack is known as LIFO?
Ex No. 8 Write a program to implement queue and circular queue using array.
Simple queue:
Insertion operation: enqueue(): The enqueue() is a data manipulation operation that is used
to insert elements into the stack. The following algorithm describes the enqueue() operation
in a simpler way.
Algorithm:
1 − START
2 – Check if the queue is full.
3 − If the queue is full, produce overflow error and exit.
4 − If the queue is not full, increment rear pointer to point the next empty space.
5 − Add data element to the queue location, where the rear is pointing.
6 − return success.
7 – END
Deletion Operation: dequeue(): The dequeue() is a data manipulation operation that is used
to remove elements from the stack. The following algorithm describes the dequeue()
operation in a simpler way.
Algorithm:
1 – START
2 − Check if the queue is empty.
3 − If the queue is empty, produce underflow error and exit.
4 − If the queue is not empty, access the data where front is pointing.
5 − Increment front pointer to point to the next available data element.
6 − Return success.
7 – END
Circular Queue:
Algorithm for insertion in queue
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
data = queue[front]
front ← front + 1
return true
end procedure
Viva Questions:
1. What is queue?
2. Types of queue?
3. Explain Operations in queue?
4. How to insert and delete the elements in simple queue?
5. How to insert and delete the elements in circular queue?
Ex. No. 9 Write a program to insert an element in the beginning and end of singly
linked list.
Aim: To understand the concept of Singly Link List and implement a program for
Insertion operations.
Theory:
Linked list is a collection of Nodes. Each node having two parts. First part represents
value of the node and second part represents an address of the next node. If Next node is
not present then it contains NULL value.
Algorithm of Insertion:-
In a singly linked list, the insertion operation can be performed in three ways. They are as
follows:-
Insertion at Beginning of the list
Insertion at End of the list
Insertion at Specific location in the list
Viva Questions:-
1. What is singly linked list?
2. What are the advantages of singly linked list?
Ex. No.10 Write a program to insert an element at any position in singly and doubly
linked list.
Aim: To understand the concept of insert an element at any position in singly and
doubly linked list.
Theory:
Inserting At Specific location in singly linked list (After a Node)
Step 1: if ptr = null(write overflow goto step 12 end of if)
Step 2: set new_node = ptr
Step 3: new_node → data = val
Step 4: set temp = head
Step 5: set i = 0
Step 6: repeat step 5 and 6 until i<loc< li=""></loc<>
Step 7: temp = temp → next
Step 8: if temp = null(write “desired node not present” goto step 12 ,end of if, end of loop)
Step 9: ptr → next = temp → next
Step 10: temp → next = ptr
Step 11: set ptr = new_node
Step 12: exit
Viva Questions:
1. Explain singly linked list.
2. Explain doubly linked list.
3. Insert an element in singly linked list after a specific location and node.
4. Insert an element in doubly linked list after a specific location and node.
Ex. No. 11. Insert and delete a node at any position in doubly linked list.
Aim: To understand the concept of insertion and deletion a node at any position in
doubly linked list.
Theory :
Algorithm :
Insertion
Step 1: if ptr = null (write overflow and Go to step 15 [end of IF])
Step 2: set new_node = ptr
Step 3: set ptr = ptr -> next
Step 4: set new_node -> data = val
Step 5: set temp = start
Step 6: set i = 0
Step 7: repeat 8 to 10 until i<="" li="">
Step 8: set temp = temp -> next
Step 9: if temp = null
Step 10: write "less than desired no. of elements" (Goto Step 15 [end of IF] [end of Loop]).
Step 11: set new_node -> next = temp -> next
Step 12: set new_node -> prev = temp
Step 13 : set temp -> next = new_node
Step 14: set temp -> next -> prev = new_node
Step 15: exit
Deletion
1.If the head of the list is NULL, that means the list is empty or if Nnext), now the next node
of del has become pointer_to_head** node.
2.Check if the node to be deleted is not the first node, then update next of the previous node
of del del->prev->next = del->next.
3.Also check, if the node to be deleted is not the last, then update the prev pointer of the next
node of del del->next->prev = del->prev and delete the del node.
4.Finally, output the desired linked list.
Viva Questions:
1. Explain doubly linked list.
2. Insert an node in doubly linked list after a specific location.
1. START
2. Procedure Hanoi(disk, source, dest, aux)
3. IF disk == 1, THE
4. move disk from source to dest
5. ELSE
6. Hanoi(disk - 1, source, aux, dest) // Step 1
7. move disk from source to dest // Step 2
8. Hanoi(disk - 1, aux, dest, source) // Step 3
9. END IF
10. END Procedure
11. STOP
Viva Questions:
1. What is the objective of tower of hanoi puzzle?
2. What is time complexity of the solution tower of hanoi problem using recursion ?
3. Minimum number of moves required to solve a tower of hanoi problem with n disks ?
4. Space complexity of recursive solution of tower of hanoi puzzle .
Ex. No.13. Write a program that uses functions to perform the following: a) Create a
binary search tree of integers. b) Traverse the above Binary search tree non recursively
in in order
Algorithm:
struct node* newNode(int item) {
struct node* temp = (struct node*) malloc (sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp; }
Viva Questions:
1.Explain binary search tree?
2.How to create a binary search tree?
3.Advantages of binary search tree?
4.Disadvantages of binary search tree?
5.Time and space complexity of creating, inserting, deleting, searching a node in binary
search tree?
6.How to traverse the binary search tree?