0% found this document useful (0 votes)
51 views11 pages

Data Structure

A linked list is a linear data structure where each element points to the next. It supports efficient insertion/deletion at the beginning by updating the head pointer. Queues follow FIFO where elements are added to the rear and removed from the front. Binary trees can be skewed, full, or complete depending on how nodes are distributed across levels. Dijkstra's algorithm finds shortest paths in graphs by assigning temporary distance labels and updating smaller distances, making the shortest path permanent on each iteration. Breadth-first search uses a queue to explore all neighbors of a node before moving to the next level, while depth-first search fully explores each branch before backtracking.

Uploaded by

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

Data Structure

A linked list is a linear data structure where each element points to the next. It supports efficient insertion/deletion at the beginning by updating the head pointer. Queues follow FIFO where elements are added to the rear and removed from the front. Binary trees can be skewed, full, or complete depending on how nodes are distributed across levels. Dijkstra's algorithm finds shortest paths in graphs by assigning temporary distance labels and updating smaller distances, making the shortest path permanent on each iteration. Breadth-first search uses a queue to explore all neighbors of a node before moving to the next level, while depth-first search fully explores each branch before backtracking.

Uploaded by

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

INTERNAL ASSIGNMENT

DATA STRUCTURES AND ALGORITHM

SET-I
1.
A). What is a linked list? Discuss the algorithms for the insertion and deletion of values in the
beginning of a linked list.
Ans: A linked list is a data structure where the objects are arranged in a linear order. Unlike an array,
however, in which the linear order is determined by the array indices, the order in a linked list is determined
by a pointer in each object.

 Insertion: To add a node at the given position.


 Deletion: To delete a node.

Linked List node Insertion


There can be three cases that will occur when we are inserting a node in a linked list.

 Insertion at the beginning


 Insertion at the end. (Append)
Insertion at the beginning
Since there is no need to find the end of the list. If the list is empty, we make the new node as the head of
the list. Otherwise, we have to connect the new node to the current head of the list and make the new
node, the head of the list.

/ function is returning the head of the singly linked-list


Node insertAtBegin(Node head, int val)
{
newNode = new Node(val) // creating new node of linked list
if(head == NULL) // check if linked list is empty
return newNode
else // inserting the node at the beginning
{
newNode.next = head
return newNode
}
}

Divyanshu Gusain 2114504447 DCA1202


Insertion at end
We will traverse the list until we find the last node. Then we insert the new node to the end of the list.
Note that we have to consider special cases such as list being empty.

In case of a list being empty, we will return the updated head of the linked list because in this case, the
inserted node is the first as well as the last node of the linked list.

// the function is returning the head of the singly linked list


Node insertAtEnd(Node head, int val)
{
if( head == NULL ) // handing the special case
{
newNode = new Node(val)
head = newNode
return head
}
Node temp = head
// traversing the list to get the last node
while( temp.next != NULL )
{
temp = temp.next
}
newNode = new Node(val)
temp.next = newNode
return head
}

Linked List node Deletion


To delete a node from a linked list, we need to do these steps

 Find the previous node of the node to be deleted.


 Change the next pointer of the previous node
 Free the memory of the deleted node.
In the deletion, there is a special case in which the first node is deleted. In this, we need to update the head
of the linked list.

Divyanshu Gusain 2114504447 DCA1202


B. Define queues and its enqueue and dequeue operations.
Ans: Queues A queue is a helpful organization in programming. it's the same as the price ticket queue
outside a cinema hall, wherever the primary person getting into the queue is that the person who gets the
ticket. There are four differing kinds of queues: easy Queue. Circular Queue.
Enqueue: Add a component to the tip of the queue. Dequeue: take away an element from the front of the
queue. IsEmpty: Check if the queue is empty. A Dequeue operation could involve the subsequent steps:
Checks that the queue is empty or not. If the queue is empty then it produces a mistake and exit.
·If the queue isn't empty then accesses the info part at that front is pointing.
·Delete the element, victimization array.pop () operation on buffer.
·Return success.
2. a. What are Binary trees? How many types of Binary trees are there, discuss?
Ans: A binary tree is a special case of a tree in which no node in a tree can have a degree greater than two.
Hence a binary tree is a set of zero or more nodes T such that:
i) There is a specially designated node called the root of the tree
ii) The remaining nodes are divided into two separate sets, T1 and T2, each of which is a binary tree. T1 is
called the left subtree and T2 the right subtree.

B). Discuss Dijkstra's shortest path algorithm

Figure: Binary tree structure


Divyanshu Gusain 2114504447 DCA1202
Types of Binary Tree Now we are going to discuss few very important types of binary tree.
1) Skewed binary tree
2) Full binary tree
3) Complete binary tree
Skewed binary tree
A binary tree that has solely left subtree is termed left inclined tree and has only right subtree is called right
skewed tree as shown within the figure. inclined trees don't seem to be economical in memory management
as a result of generally, an n node binary tree desires an array whose length is between n+1 and 2n, however
whereas storing skewed binary tree it wastes most of the memory area.

Figure: Skewed trees


Full binary tree
A binary tree is a full binary tree if and only if :- o Each non leaf node has exactly two child nodes o All leaf
nodes are at the same level A full binary tree is a binary of depth k having 2k − 1 nodes as referred in the
figure 4.5. If it has < 2k − 1, it is not a full binary tree. For example, for k = 3, the number of nodes = 2k − 1
= 23 − 1 = 8 − 1 = 7. A full binary tree with depth k = 3 is shown in Figure.
We use numbers from 1 to 2k − 1 as labels of the nodes of the tree. If a binary tree is full, then we can
number its nodes sequentially from 1 to 2k−1, starting from the root node, and at every level numbering the
nodes from left to right.

Figure: A full binary tree


Complete binary tree
A complete binary tree is a binary tree in which all levels, except possibly the last one, are completely filled
and all nodes are as far to the left as possible. The figure shows a complete binary tree filled at each depth
from left to right.

Divyanshu Gusain 2114504447 DCA1202


Figure: Complete binary tree from left to right
b. Discuss Dijkstra’s Algorithm for the shortest path.
Ans: This formula is employed to seek out the shortest path between the 2 vertices during a weighted
directed graph and it's additionally very common and economical to find every and each path from
beginning (source) to terminal vertices.
Let w(vi , vj ) be the load related to every edge (vi , vj ) in a given weighted directed graph G. allow us to
outline that the weights are such the entire weight from vertex vi to vk via vertex vj is w(vi , vj ) + w(vj ,
vk ). victimization this form of definition , the load from a vertex vs (source) to vertex VT (end of path)
within the graph G for a given path (vs , v1 ), (v1 , v2 ), (v2 , v3 )……… (vi , vt ) is given by w(vs , v1 ) +
w(v1 , v2 ) + w(v2 , v3 ) + …………..+ w(vi , vt ). thence for such a graph there is also several doable ways
between vs and vt. .
In this algorithm, labels are assigned to every vertex. Length is taken into account to be the load of the sting
if there's a position between 2 vertices. And if there are many edges then the shortest length edge is used. If
no edge truly exits then the length is about to infinity. Edge (vi , vj ) doesn't essentially have constant length
as edge (vj , vi ). This reality permits that the various ways with different weights is there in between two
vertices relying upon their direction of travel. The time needed by Dijkstra's formula is O(|V|2).
Since label is assigned to every vertex, the label is adequate the gap (weight) from the beginning vertex to
the top vertex. The starting vertex vs is meant to possess label 0. A label is either temporary or permanent.
Temporary label is one that has uncertainty on the shortest path wherever as permanent label lies along the
shortest path.
Dijkstra’s algorithm is given below in stepwise manner:
Step 1: Assign a temporary label 1 (vi ) = ∞ to all vertices except vs
Step 2: Mark vs as permanent by assigning 0 label to it
1(vs ) = 0
Step 3: Assign value of vs to vr where vr is last vertex to be
madepermanent. Vr = Vs
Step 4: If 1 (vi ) > 1 (vk ) + w(vk , vi ).
1 (vi ) = 1 (vk ) + w(vk , vi ).
Step 5: vr = vi
Step 6: If vt has temporary label, repeat step 4 to step 5 otherwise the
valueof vt is permanent label and is equal to the shortest path
vs to vt .
Step 7: Exit.

Divyanshu Gusain 2114504447 DCA1202


3. Explain Breadth-first search and Depth-first search algorithms in graphs.
Ans: Breadth-first search: This algorithmic rule uses a queue arrangement to perform the search. The
result of this can be to method all nodes adjacent to the beginning node before we tend to process the nodes
adjacent to those nodes.
If all of the perimeters in an exceedingly graph are unweighted (or constant weight) then the primary time a
node is visited is that the shortest path thereto node from the supply node.
Algorithms for Breadth first search is additionally kind of like the one that's mentioned within the previous
unit. The conception of algorithm is same either or not it's in trees or in graph.
There are other algorithmic rules wont to realize the shortest path from one node to a different like Dijkstra's
algorithm. The shortest path from every node to each other node is additionally solved mistreatment the
Floyd algorithm, Warshall algorithm and changed Warshall algorithms.
Depth initial search: The depth first search algorithm is employed to go to all of the nodes within the graph
for its examination and not invariably necessary to find the shortest path. Depth first search is completed by
taking a node, checking its neighbors, increasing the primary node it finds among the neighbors, checking if
that dilated node is our destination, and if not, continue exploring additional nodes.
In Depth initial search it ought to be noted that very same node isn't visited over once, otherwise chance of
infinite formula could occur. Algorithms for Depth first search is comparable to the one that's mentioned in
the previous unit. The conception of algorithmic rule is same either or not it's in trees or in graph.

Divyanshu Gusain 2114504447 DCA1202


SET – 2
4.
A). Explain the algorithms of Sequential Searching and Binary Searching.
Ans: Sequential Searching: The simplest type of search process is sequential search or linear search. In
sequential search, each element in the array is compared to the key in the order in which it appears in the
array, until the first element that matches the key is found. If you are looking for an element that is near the
beginning of the array, sequential search will find it quickly. The more data there is to look up, the longer it
takes to find the data that matches the key using this technique.
For a list of n items, the best case is when the value is equal to the first item in the list, in which case only
one comparison is needed.
The worst case is when the value is not in the list (or only appears once at the end of the list), in which case
n comparisons are required. The input to a search algorithm is an array of objects A, the number of objects
n, and the key value x to search for. Here we will discuss linear search in ordered and unordered lists.
Binary Searching: Let's discuss another search that is very efficient, especially when you need to search for
more objects. Binary search is one of the fastest ways to search for the element in a sorted array. The idea is
to look at the element in the middle. If the key is equal to this element, then the search is over. If the key is
less than the middle element, do a binary search on the first half.
If it's larger than the middle element, do a binary search on the second half.
Now consider the following array for binary search.
Consider executing the algorithm Binary-Search [A, 8, 34]. The variable high is initially set to 8, and since
low (i.e., 1) is less than or equal to high, mid is set to (low + high)/2 = 9/2 = 4.
i 12345678

A 10 11 12 16 34 37 54 65

B). What are the characteristics and Building Blocks of an Algorithm?


Ans: Characteristics of an Algorithm
Finiteness
An algorithm must terminate after a finite number of steps and further each step must be executable in finite
amount of time. In order to establish a sequence of steps as an algorithm, it should be established that it
terminates (in finite number of steps) on all allowed inputs.
Definiteness (no ambiguity)
Each step of an algorithm must be precisely defined; the action to be carried out must be rigorously and
unambiguously specified for each case. However, the method is not definite, as two different executions
may yield different outputs.
Building Blocks of an Algorithm:
The following three basic actions and corresponding instructions form the basis of any imperative language.
For the purpose of explanations, the notation similar to that of a high level programming language is used.
Basic Actions & Instructions

Divyanshu Gusain 2114504447 DCA1202


i) Assignment of a value to a variable is denoted by Variable - expression;
Where the expression is composed from variable and constant operands using familiar operators like +, –, *
etc.
Assignment action includes evaluation of the expression on the R.H.S. An example of assignment
instruction/ statement is
j - 2 * i + j – r; It is assumed that each of the variables occurring on R.H.S of the above statement, has a
value associated with it before the execution of the above statement. The association of a value to a variable,
whether occurring on L.H.S or on R.H.S, is made according to the following rule.
For each variable name, say i, there is a unique location, say loc 1
(i), in the main memory. Each location loc
(i), at any point of time contains a unique value say v
(i). Thus the value v
(i) is associated to variable i.
Using these values, the expression on R.H.S is evaluated. The value so obtained is the new value of the
variable on L.H.S. This value is then stored as a new value of the variable (in this case, j) on L.H.S. It may
be noted that the variable on L.H.S (in this case, j) may also occur on R.H.S of the assignment symbol.
ii) The next basic action is read values of variables i, j, etc. from some secondary storage device, the identity
of which is (implicitly) assumed here, by a statement of the form read (i j, ); The values corresponding to
variables i, j, ... in the read statement, are, due to read statement, stored in the corresponding locations loc
(i), loc(j) ...., in the main memory.
iii) The last of the three basic actions is to deliver/ write values of some variables say i, j etc. to the monitor
or to an external secondary storage by a statement of the form Write (i, j,….);

5. a. How is the Efficiency of an Algorithm measured?


Ans: If a tangle is algorithmic ally soluble then it's going to have quite one formulaic solution. Mainly, a
pair of} pc resources taken into thought for potency measures are time and house necessities for execution
the program like the solution/algorithm. we'll limit to solely time complexities of algorithms of the
problems.
It is straightforward to understand that given an algorithm for multiplying two n x n matrices, the time
needed by the algorithm for locating the merchandise of two 2 x 2 matrices, is anticipated to require a lot of
less time than the time taken by a similar formula for multiplying, say, 2 a hundred x 100 matrices. This
explains intuitively the notion of the scale and instances of a tangle and additionally the role of size in
crucial the (time) complexness of algorithm. If the size of general instance is n then time complexity of the
algorithm resolution the matter into account is a few operate of n.
B). What is Divide and conquer strategy?
Ans: Given a perform to calculate on n inputs, the divide-and-conquer strategy suggests rending the inputs
into K distinct subsets, one
We can write an impression abstraction that mirrors the method associate formula supported divide-and-
conquer can look. By control abstractions we have a tendency to mean a procedure whose flow of control is
obvious however whose primary operations are such by different procedures whose precise meanings are
left indefinite.
Divyanshu Gusain 2114504447 DCA1202
Algorithm 1
1.procedure DANDC (p,q)
2.global integer n, A(1:n)
3.integer p,q; //1 p  q  n//
4.local integer m;
5.if small (p,q)
6.then return (G(p,q))
7.else m  divide (p,q) //p < m < q
8.return (combine(DANDC(p,m), DANDC(m + 1,q)))
9.endif
10.end DANDC
In Algorithm 1, procedure is called by DANDC (1,n)
– Small (p,q) is a Boolean function and will return true or false. True if input size is small enough that the
answer can be computed without splitting. If so, function G is invoked.
– Divide (p,q), divides into (p, m) and (m+1, q)
– Combine function combines the results of p,m and m+1, q. Combine is a function that determines the
solution to p using the solutions to the K sub problems.
If the size of p is n and the sizes of the K subproblems are n1, n2…, nk respectively, then the computing
time of DANDC is described by the recurrence relation.

6. Discuss the Greedy knapsack Algorithm, with a suitable


Ans: The greedy algorithm could be very well understood using a known problem known as the knapsack
problem. Although the same problem could be solved with other algorithmic approaches, the greedy
approach solves the fractional knapsack problem in reasonable time.
We get a set of n jobs . Associated with the job i is an integer deadline di> 0 and a profit pi> 0. For each job
i, profit pi is obtained if the job is completed before the deadline.
To complete an order, the order must be processed on one machine for a unit of time. Only one machine is
available to process orders.
Algorithm 1 demonstrates the greedy algorithm for sequencing time unit jobs with deadlines and revenue
Algorithm 1
1. Algorithm JS (d,j,n)
2. //d[i]1, 1 in are the deadlines, n1. The jobs
3. // are ordered such that p[1] p[2]  ....p[n].
4. //J[i] is the ith job in the optimal solution, 1 ik.
5. //Also, at termination d [J[i]] d[J[i+1]], 1 ik.
6. {
7. d[0]:=J[0]:=0;//lnitialize
8. J[1]:=1 ;// include job 1
9. K:=1;
10. for i:=2 to n do
11. {
12. //Consider jobs in non-increasing order of p[i]
13. //Find position for i and check feasibility for insertion
14. r:=k;
15. While((d[J[r]]>d[i]) and (d[J[r]]r)) dp r:= r – 1;
16. if ((d[J[r]] d[i]) and (d[i]>r)) then
17. {
18. // Insert i into J[ ].
19. for q:=k to (r+1) step – 1 do J[q+1]:=J[q];
20. J[r+1]:=i; k:=k+1;
Divyanshu Gusain 2114504447 DCA1202
21. }
22. }
23. return k;
24. }
Example: // C/C++ program to solve fractional Knapsack Problem
#include <bits/stdc++.h>
  
using namespace std;
  
// Structure for an item which stores weight and
// corresponding value of Item
struct Item {
    int value, weight;
  
    // Constructor
    Item(int value, int weight)
    {
        this->value = value;
        this->weight = weight;
    }
};
  
// Comparison function to sort Item according to val/weight
// ratio
bool cmp(struct Item a, struct Item b)
{
    double r1 = (double)a.value / (double)a.weight;
    double r2 = (double)b.value / (double)b.weight;
    return r1 > r2;
}
  
// Main greedy function to solve problem
double fractionalKnapsack(int W, struct Item arr[], int n)
{
    //    sorting Item on basis of ratio
    sort(arr, arr + n, cmp);
  
    //    Uncomment to see new order of Items with their
    //    ratio
    /*
    for (int i = 0; i < n; i++)
    {
        cout << arr[i].value << "  " << arr[i].weight << " :
    "
             << ((double)arr[i].value / arr[i].weight) <<
    endl;
    }
    */
  
    double finalvalue = 0.0; // Result (value in Knapsack)
  
    // Looping through all Items
    for (int i = 0; i < n; i++) {
Divyanshu Gusain 2114504447 DCA1202
        // If adding Item won't overflow, add it completely
        if (arr[i].weight <= W) {
            W -= arr[i].weight;
            finalvalue += arr[i].value;
        }
  
        // If we can't add current Item, add fractional part
        // of it
        else {
            finalvalue
                += arr[i].value
                   * ((double)W / (double)arr[i].weight);
            break;
        }
    }
  
    // Returning final value
    return finalvalue;
}
  
// Driver code
int main()
{
    int W = 50; //    Weight of knapsack
    Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    cout << "Maximum value we can obtain = "
         << fractionalKnapsack(W, arr, n);
    return 0;
}

Output
Maximum value we can obtain = 240

Divyanshu Gusain 2114504447 DCA1202

You might also like