Data Structures Se E&Tc List of Practicals
Data Structures Se E&Tc List of Practicals
SE E&TC
List of Practicals
1) Searching methods-Linear & Binary
Aim of Experiment:
Write a menu driven program to perform following searching operations:
1) Linear search.
2) Binary search.
Objectives:
After performing this experiment, student should be able to understand the
concept of a various Searching methods.
Write functions for other simple searching methods like Fibonacci search.
Theory:
1) Binary search:
In its simplest form, binary search is used to quickly find a value in a sorted sequence
(consider a sequence an ordinary array for now). We'll call the sought value the target
value for clarity. Binary search maintains a contiguous subsequence of the starting
sequence where the target value is surely located. This is called the search space. The
search space is initially the entire sequence. At each step, the algorithm compares the
median value in the search space to the target value. Based on the comparison and
because the sequence is sorted, it can then eliminate half of the search space. By doing
this repeatedly, it will eventually be left with a search space consisting of a single
element, the target value.
For example, consider the following sequence of integers sorted in ascending order and
say we are looking for the number 55:
0 5 13 19 22 41 55 68 72 81 98
We are interested in the location of the target value in the sequence so we will represent
the search space as indices into the sequence. Initially, the search space contains indices
1 through 11. Since the search space is really an interval, it suffices to store just two
numbers, the low and high indices. As described above, we now choose the median
value, which is the value at index 6 (the midpoint between 1 and 11): this value is 41 and
it is smaller than the target value. From this we conclude not only that the element at
index 6 is not the target value, but also that no element at indices between 1 and 5 can
be the target value, because all elements at these indices are smaller than 41, which is
smaller than the target value. This brings the search space down to indices 7 through 11:
55 68 72 81 98
Proceeding in a similar fashion, we chop off the second half of the search space and are
left with:
55 68
Depending on how we choose the median of an even number of elements we will either
find 55 in the next step or chop off 68 to get a search space of only one element. Either
way, we conclude that the index where the target value is located is 7.
If the target value was not present in the sequence, binary search would empty the
search space entirely.
2) Linear search:
In computer science, linear search or sequential search is a method for finding a
particular value in a list , that consists in checking every one of its elements, one at a
time and in sequence, until the desired one is found.
For a list with n items, the best case is when the value is equal to the first element of the
list, in which case only 1 comparison is needed. The worst case is when the value is not
in the list (or occurs only once at the end of the list), in which case n comparisons are
needed.
Analysis of Linear Search:
The way in which big O is determined for a particular algorithm is algorithm analysis.
Take for example the simple linear search algorithm that we mentioned previously and
apply it to the value 3 and the ordered set .
Sequentially the algorithm would start from the index of the set, 0, and then look at each
next value until it finds the value 3, thus making four comparisons.
Aim of Experiment:
Implement the following Sort Methods:
1. Bubble sort
2. Insertion sort
3. Selection sort.
Display results after every pass along with no. of comparisons and exchanges for already
sorted input and unsorted data.
Objective:
This assignment is designed to implement different sorting methods. Analyze the
given algorithms.
Theory:
1) Bubble sort:
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the
list to be sorted, comparing each pair of adjacent items and swapping them if they are in
the wrong order. The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted. The algorithm gets its name from the way smaller
elements "bubble" to the top of the list. Because it only uses comparisons to operate on
elements, it is a comparison sort.
Analysis of Bubble Sort:
Bubble sort has best-case complexity Ω (n). When a list is already sorted, bubble sort will
pass through the list once, and find that it does not need to swap any elements. Thus
bubble sort will make only n comparisons and determine that list is completely sorted. It
will also use considerably less time than О (n²) if the elements in the unsorted list are not
too far from their sorted places. The worst case complexity is O (n2).
Efficiency:
For each pass the number of elements scanned for comparisons reduces by 1.
Number of comparisons in the first pass =(n-1)
Number of comparisons in the Second pass =(n-2)
Number of comparisons in the last pass =1
Thus the total number of comparisons at the end of the algorithm would have been
(n-1) + (n-2) +(n-3)+…+2+1= n(n-1)/2 =n2 /2 +O(n) = O(n2)
Hence the order of the bubble sort algorithm is O(n2) in worst case
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to
greatest number using bubble sort algorithm. In each step, elements written in bold are
being compared.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
(14258)(14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458)(12458)
(12458)(12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458)(12458)
(12458)(12458)
(12458)(12458)
(12458)(12458)
Finally, the array is sorted, and the algorithm can terminate.
Algorithm:
1. Bubble Sort:
Given array K of N elements, algorithm sorts the elements in
increasing(ascending) order. The variables Pass & Last denote pass counter &
position of last unsorted element respectively. I is index of array elements and
EXCHs is to count no of exchanges made by any pass.
1. (Initialize)
Last =N
2. (Loop)
Repeat through step 5 for Pass= 1,2,…N-1
3. (Initialize Exchanges counter for this Pass)
EXCHS=0
4. Repeat for I=1,2,….,Last-1
If K[I]>K[I+1]
Then swap (K[I] & K[I+1])
EXCHS=EXCHS+1
5. (Were any exchanges made on this pass?)
If EXCHS==0
Then Return // mission accomplished; return early
FAQ:
What is sorting?
What is recursion?
What is difference between selection, insertion, and bubble sort methods?
What are the applications?
References:
1. ‘C programming’ by Balguruswami.
2. ‘ Let us C’ Kanetkar.
3. ‘Fundamentals of data structures” sartaj sahani.
Conclusion:
Theory:
A constructed data type know as structure which is method for packing data of different
types is convenient tool for handling a group of logically related items. A structure is a
collection of data fields or variables of different types that is referenced under the same
name. It provides convenience means of keeping related information which are called
fields of members can be accessed and processed separately.
Defining a Structure
A structure type is usually defined near to the start of a file using a typedef statement.
typedef defines and names a new type, allowing its use throughout the program.
typedefs usually occur just after the #define and #include statements in a file.
Structure definition:
typedef struct student
{
int roll no;
char name[20];
int marks;
}student;
Here are examples of structure definition.
1) Without using typedef
struct Bankcust {
char name[15];
char address[20];
int balance;
int acno;
};
In this case the variables are declared as follows:
struct Bankcust cust;
2) Using typedef to have shorter name while declaring variables:
typedef struct {
char name[15];
char address[20];
int balance;
int acno;
} Bankcust;
This defines a new type cust variables of type Bankcust can be declared as follows.
Bankcust cust;
Notice how similar this is to declaring an int or float.
The variable name is cust, it has members called name, address, balance and acno.
Algorithm:
1) Get no of students from user.
2) Store information of each student in database.
3) Display the student’s information.
4) Search student information.
5) Update.
6) Insert new student.
7) Delete student information.
Data structure and variables used:
Student structure is used to store student information like roll no, name and marks.
St[30] is array of structure used to store student info. of the class.
is used to store number of students.
I is used for loop to define index variable.
Input:
Add records to the student database
Select Operation to be performed.
Output :
Perform operations like add, search, modify, delete, display list, display record depending
on the operation selected and manipulate the database when required.
Application:
1) Used to store student information in college account section.
2) Used to store student information in college library section.
3) Used to represent the various databases.
Program Listing:
/*Program for Operations on a database */
OUTPUT:
FAQ:
What is structure?
What is database?
What are the different operations we perform on database?
References:
1. ‘C programming’ by Balguruswami.
2. ‘Fundamentals of datastructures” sartaj sahani.
Conclusion:
Aim of Experiment:
Write a program to implement polynomial addition using array of structure.
Objective:
i) To know algorithm for addition of two single variable polynomial.
ii) To implement algorithm.
iii) To display the resultant polynomial.
Theory:
A polynomial is either zero, or can be written as the sum of one or more non-zero terms.
The number of terms is finite. These terms consist of a constant (called the coefficient of
the term) multiplied by zero or more variables (which are usually represented by letters).
Each variable may have an exponent that is a non-negative integer (also known as a
natural number). The exponent on a variable in a term is equal to the degree of that
variable in that term. Since x = x1, the degree of a variable without a written exponent is
one. A term with no variables is called a constant term, or just a constant. The degree of
a constant term is 0. The coefficient of a term may be any number, including fractions,
irrational numbers, negative numbers, and complex numbers. We are stored the
polynomials i.e. coefficient and power by using structure variables. And add them and
result is displayed.
Structure definition for polynomial:
typedef struct poly
{ int coeff;
int expo;
}p;
p p1[10],p2[10],p3[10];
Algorithm:
1) Start
2) Take the total no of terms in polynomial i.e.t1,t2
3) Enter the coeff. and expo.in descending order.
4) Steps for addition of two polynomial:
i) Check the exponents of two polynomial for same,
If same then add the coefficients.
if(p1[i].expo==p2[j].expo)
p3[k].coeff=p1[i].coeff+p2[j].coeff;
and store result in to 3rd polynomial with the exponent == expo.of any term i.e.
p3[k].expo=p1[i].expo;
ii) If exponent of the term of 1st polynomial is greater than the 2nd then :
else if(p1[1].expo>p2[j].expo)
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
iii) Else exponent of the term of 2nd polynomial is greater than the 1st
then:
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
iv) If there is only 1st polynomial entered then
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
v) If there is only 2nd polynomial entered then
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
vi) Return the result to main function:
return(t3);
5) Stop.
Operations:
1) Read the choice from user.
2) Read 1st polynomial.
3) Read 2nd polynomial.
4) Perform addition.
5) Display result.
OUTPUT:
References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:
A linked list whose nodes contain two fields: an integer value and a link to the next node
Linked lists are among the simplest and most common data structures, and are used to
implement many important abstract data structures, such as stacks, queues, hash
tables, symbolic expressions, skip lists, and many more.
The principal benefit of a linked list over a conventional array is that the order of the
linked items may be different from the order that the data items are stored in memory or
on disk. For that reason, linked lists allow insertion and removal of nodes at any point in
the list, with a constant number of operations.
On the other hand, linked lists by themselves do not allow random access to the data, or
any form of efficient indexing. Thus, many basic operations — such as obtaining the last
node of the list, or finding a node that contains a given data, or locating the place where
a new node should be inserted — may require scanning most of the list elements.
Singly-linked list:
Linked list is a very important dynamic data structure. Basically, there are two types of
linked list, singly-linked list and doubly-linked list. In a singly-linked list every element
contains some data and a link to the next element, which allows to keep the structure.
On the other hand, every node in a doubly-linked list also contains a link to the
previous node. Linked list can be an underlying data structure to implement stack,
queue or sorted list.
Example
Sketchy, singly-linked list can be shown like this:
Each cell is called a node of a singly-linked list. First node is called head and it's a
dedicated node. By knowing it, we can access every other node in the list. Sometimes,
last node, called tail, is also stored in order to speed up add operation.
Singly-linked list. Internal representation:
Every node of a singly-linked list contains following information:
• A value (user's data);
• A link to the next element (auxiliary data).
Sketchy, it can be shown like this:
First node called head and no other node points to it. Link to the head is usually
stored it the class, which provides an interface to the resulting data structure. For
empty list, head is set to NULL.
Also, it makes sense to store a link to the last node, called tail.
Algorithm:
Insertion in ordered list:
// x is the data element of the node to be inserted in linked list
// list is the starting node of the linked list
// next refers to the next node of the linked list
// info refers to info field of the node
Getnode (new)
Info (new) =x
next (new) =null
if list = null
list = new
else
begin
p=list
if x < info (p)
then next (new) = list
list = new
else
begin
while (next (p) <> null) and (x >= info (next (p))) do
p= next (p)
if (current = null)
call print(“ node with the given value doesn’t exist in the
list”)
else
display the position and the content of the node
OUTPUT:
FAQS :
o How it is useful in different application.
o What are the different ways to implement it.
o How to allocate dynamic memory.
References :
• “C programming “ Balguruswamy.
• ‘Fundamentals of datastructures” sartaj sahani.
• “Data structures “ Tananbom
Conclusion:
Pop(int S [])
// TOP as pointer which keep track of the top element in the stack.
// This algorithm gives push item in stack A
// Pre – S is stack
// Post – item is poped in S stack
// Return –item which is top element of a stack.
begin
if top<= 0 then
call stack_empty()
return
end //if
Stack_empty()
// TOP as pointer which keep track of the top element in the stack.
If (top == zero)
Call print(“stack is empty”);
End //if
End stack_empty;
Stack_full()
// TOP as pointer which keep track of the top element in the stack.
If (top == n)
Call print(“stack is full”);
End //if
End Stack_full;
Begin
counter =top
While counter >0
Call print(s[counter])
counter—
end //while
end Stack_display
Input:
Input is the data/number that is to be pushed on the stack.
Output:
Output is the data/element popped from the stack.
Applications :
• Expression conversion and evaluation
• Reversing a string
• Parsing
• Well formed Parenthesis.
• Decimal to binary conversion.
Program Listing:
/* stack in an array */
OUTPUT:
FAQs :
• How it is useful in different application.
• What are the different ways to implement it.
• What are the limitations of stack.
Conclusion:
Thus we have studied various operations like push, pop, display on stack.
Objective :
This assignment will help the student to realize the implementation difference
between stack and queue. Also this will clear the implementation concepts queue.
Theory:
The queue data structure is characterized by the fact that additions are made end, or
tail, of the queue while removals are made from the front, or head, of the queue. For this
reason, a Queue is referred to as a FIFO structure (First-In First-Out). Queues occur
naturally in situations where the rate at which clients’ demand for services can exceed
the rate at which these services can be supplied. For example, in network where many
computers share only a few printers, the print jobs may accumulate in print queue. In an
operating system with a GUI, applications and window communicate using messages,
which are placed in message queues until they can be handled.
Operations:
The main primitive operations of a queue are known as:
Add : adds a new node
Remove: removes a node
Struct queue
{
Int q[MAX];
Int front,rear;
}
Dynamic implementation of queue:
Linked representation is used for dynamic implementation of queue,
In linked representation there is no memory constraint. size can be increased at run
time.
We can also release the memory when the element is removed from queue.
To create queue using Linked representation following steps are implemented:
1) Front and rear are NODE type pointer, which are NULL.
2) Whenever new node is created set rear to new.
3) Whenever node is to be deleted store address of front into temp and decrease
front and release the temp.
Struct node
{ int data;
Struct nide * link;
}
Input :
Input is the data/element that is to be added to the queue.
Output:
Output is the data/element removed from the queue, data elements in the queue.
Application :
• Job scheduling in compiler.
• Queue simulation.
OUTPUT:
FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of Queue.
References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:
Aim of Experiment:
Take postfix expression as a input and evaluate it for result.
Objective :
This assignment will help the student to know how the postfix expression
evaluation.
Theory:
The expression a + b*(c - d )+ e written in postfix form is abcd - * + e +. This looks
rather cryptic. You can get the idea most easily if you read it backwards as `` add e to
(add (times (c - d) and b) to a)''. A few more examples are shown in Table which may
serve better than an elaborate explanation:
Table: Converting expressions to postfix
notation.
a+(b+c) abc++
(a+b)+c ab+c+
a-b*c abc*-
(a/b)*(c/d) ab/cd/*
a/(b+c*d-e) abcd*+e-/
a-b*c+d/e abc*-de/+
Algorithm:
Postfix Expression :
STEP 1 : Read the given postfix expression into a string called postfix.
STEP 2 : Read one character at a time & perform the following operations :
1. If the read character is an operand, then convert it to float and
push it onto the stack.
2. If the character is not an operand, then pop the operator from stack
And assign to OP2. Similarly, pop one more operator from stack
and assign to OP1.
STEP 3 : Repeat STEP 2 till all characters are processed from the input string.
STEP 4 : Return the result from this procedure or algorithm and display the
result in main program.
In normal algebra we use the infix notation like a+b*c. The corresponding postfix
notation is abc*+. The algorithm for the evaluation of postfix ex. is as follows :
Scan the Postfix string from left to right.
Initialize an empty stack.
If the scanned character is an operand, add it to the stack. If the scanned
character is an operator, there will be at least two operands in the stack.
o If the scanned character is an Operator, then we store the top most
element of the stack(topStack) in a variable temp. Pop the stack. Now
evaluate topStack(Operator)temp. Let the result of this operation be
retVal. Pop the stack and Push retVal into the stack.
o Repeat this step till all the characters are scanned.
After all characters are scanned, we will have only one element in the stack.
Return topStack.
Input:
Input is the postfix expression which we want to evaluate.
Output:
Output is the result of postfix expression.
OUTPUT:
FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of it.
References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:
In computer science a binary search tree (BST) is a node based binary tree data structure
which has the following properties:
The left sub-tree of a node contains only nodes with keys less than the node's
key.
The right sub-tree of a node contains only nodes with keys greater than the
node's key.
Both the left and right sub-trees must also be binary search trees
Traversal:
Traversal is a systematic way of retrieving information form tree in such a way that no
node will be left unvisited or no node will be visited twice or more.
There are different techniques of traversals:
1) Pre-order
2) Post-order
3) In-order
4) Depth first search
5) Breadth first
Each of these methods start processing from root of tree.
1) Pre-order: In this data on the root node will be printed first then we move on the
left sub-tree and go on printing the data till we reach to the leftmost node. Print the
data at that node and then move to the right sub-tree.
2) In-order : In this traversal first we go towards the leftmost node to print data on
that node then traversing left sub-tree then print root node then traverse right
subtree.
3) Post-order: In post order traversal we follow the LRD principle i.e. move to the
leftmost node check if right sub-tree is there or not if not then print the leftmost
node, if right sub tree is there move towards rightmost node.
Algorithm:
Algorithm for search:
Algorithm search (tree node,key)
1) If tree is empty
Return NULL.
2) If key = root of key
Return root.
3) Else If key<root of key
Return (search( root of left child, key))
4) Else
Return (search( root of right child, key))
Output:
Output is the BST and primitive operations on BST.
Application:
• priority queues
• associative arrays
Program Listing:
OUTPUT:
FAQs :
o How it is useful in different application.
o What are the different ways to implement it.
o What are the limitations of BST.
References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion:
Adjacency matrix:
In mathematics and computer science, an adjacency matrix (or one-hop connectivity
matrix) is a means of representing which vertices of a graph are adjacent to which other
vertices. Another matrix representation for a graph is the incidence matrix Specifically,
the adjacency matrix of a finite graph G on n vertices is the n × n matrix where the
nondiagonal entry aij is the number of edges from vertex i to vertex j, and the diagonal
entry aii, depending on the convention, is either once or twice the number of edges
(loops) from vertex i to itself. Undirected graphs often use the former convention of
counting loops twice, whereas directed graphs typically use the latter convention. There
exists a unique adjacency matrix for each graph (up to permuting rows and columns),
and it is not the adjacency matrix of any other graph. In the special case of a finite
simple graph, the adjacency matrix is a (0,1)-matrix m with zeros on its diagonal. If the
graph is undirected, the adjacency matrix is symmetric.
Operations:
6) Create a graph.
7) Insert new node in created graph.
8) Delete node from the graph.
9) Search a node (DFS/BFS).
Input:
1) Adjacency matrix.
2) Enter the starting vertex for DFS/BFS.
Output:
Element Found by DFS/BFS.
Program Listing:
OUTPUT:
References :
o “C programming “ Balguruswamy.
o ‘Fundamentals of datastructures” sartaj sahani.
o “Data structures “ Tananbom
Conclusion: