Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

bcs042 pdf

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

What is an algorithm? What is the need for an algorithm?

An
algorithm is a well-defined computational procedure that takes some values or
the set of values, as an input and produces a set of values or some values, as an
output. The algorithm provides the basic idea of the problem and an approach to
solve it. Some reasons to use an algorithm are as follows.1.The algorithm improves
the efficiency of an existing technique.2.To compare the performance of the
algorithm with respect to other techniques.3.The algorithm gives a strong
description of requirements and goal of the problems to the designer.4.The
algorithm provides a reasonable understanding of the flow of the
program.5.The algorithm measures the performance of the methods in
different cases (Best cases, worst cases, average cases).6.The algorithm
identifies the resources (input/output, memory) cycles required by the
algorithm.7.With the help of an algorithm, we can measure and analyze the
complexity time and space of the problems./What is the Complexity of
AlgorithmThe complexity of the algorithm is a way to classify how efficient an
algorithm is compared to alternative ones. Its focus is on how execution time
increases with the data set to be processed. The computational complexity of the
algorithm is important in computing.It is very suitable to classify algorithm based
on the relative amount of time or relative amount of space they required and
specify the growth of time/ space requirement as a function of input size.Time
complexityTime complexity is a Running time of a program as a function of the
size of the input.SpacecomplexitySpace complexity analyzes the algorithms,
based on how much space an algorithm needs to complete its task. Space
complexity analysis was critical in the early days of computing (when storage
space on the computer was limited).Worst-case: f(n)It is defined by the maximum
number of steps taken on any instance of size n.Best-case: f(n)It is defined by the
minimum number of steps taken on any instance of size n.Average-case: f(n)It is
defined by the average number of steps taken on any instance of size n./Write
an algorithm to reverse a string. For example, if my string is
"uhsnamiH" then my result will be "Himanshu".Algorithm to reverse
a string.Step1: startStep2: Take two variable i and jStep3: do length (string)-1, to
set J at last positionStep4: do string [0], to set i on the first character.Step5: string
[i] is interchanged with string[j]Step6: Increment i by 1Step7: Increment j by
1Step8: if i>j then go to step3Step9: Stop/Write an algorithm to insert a
node in a sorted linked list.Algorithm to insert a node in a sorted linked
list.Case1:Check if the linked list is empty then set the node as head and return
it.1.New_node-> Next= head; 2.Head=New_node Case2:Insert the new node in
middle1.While( P!= insert position)2.{3.P= p-> Next;4.}5.Store_next=p->Next;6.P-
>Next= New_node;7.New_Node->Next = Store_next;
Write an algorithm to insert a node in a sorted linked
list.Algorithm to insert a node in a sorted linked list.Case1:Check if the linked list
is empty then set the node as head and return it.1.New_node-
> Next= head; 2.Head=New_node Case2:Insert the new node in
middle1.While( P!= insert position)2.{3.P= p-> Next;4.}5.Store_next=p->Next;6.P-
>Next= New_node;7.New_Node->Next = Store_next;/5) What are the
Asymptotic Notations?Asymptotic analysis is used to measure the
efficiency of an algorithm that doesn't depend on machine-specific constants
and prevents the algorithm from comparing the time taking algorithm.
Asymptotic notation is a mathematical tool that is used to represent the time
complexity of algorithms for asymptotic analysis.The three most used asymptotic
notation is as follows.θ Notationθ Notation defines the exact asymptotic
behavior. To define a behavior, it bounds functions from above and below. A
convenient way to get Theta notation of an expression is to drop low order terms
and ignore leading constants.Big O NotationThe Big O notation bounds a
function from above, it defines an upper bound of an algorithm. Let's consider
the case of insertion sort; it takes linear time in the best case and quadratic time
in the worst case. The time complexity of insertion sort is O(n2). It is useful when
we only have upper bound on time complexity of an algorithm.Ω NotationJust
like Big O notation provides an asymptotic upper bound, the Ω
Notation provides an asymptotic lower bound on a function. It is useful when we
have lower bound on time complexity of an algorithm./7) How to swap two
integers without swapping the temporary variable in
Java?Suppose we have two integers I and j, the value of i=7 and j=8 then how
will you swap them without using a third variable. This is a journal problem.We
need to do this using Java programming constructs. We can swap numbers by
performing some mathematical operations like addition, subtraction,
multiplication, and division. But maybe it will create the problem of integer
overflow.Using addition and
subtraction1.a= a + b;2.b=a - b; // this will act like (a+b)-
b, now b is equal to a.3.a=a - b; // (a+b)-a, now, a is equal to b./What is a
Hash Table? How can we use this structure to find all
anagrams in a dictionary?A Hash table is a data structure for storing
values to keys of arbitrary type. The Hash table consists of an index into an array
by using a Hash function. Indexes are used to store the elements. We assign
each possible element to a bucket by using a hash function. Multiple keys can be
assigned to the same bucket, so all the key and value pairs are stored in lists
within their respective buckets. Right hashing function has a great impact on
performance.FUNCTION find_anagrams(words)word_groups = HashTable<Stri
ng, List>FOR word IN words_word_groups.get_or_default(sort(word), []).push(
word)END FORanagrams = ListFOR key, value IN word_groupsanagrams.pus
h(value)\END FOR\RETURN anagrams
What is Divide and Conquer algorithms?Divide and Conquer is not
an algorithm; it's a pattern for the algorithm. It is designed in a way as to take
dispute on a huge input, break the input into minor pieces, and decide the
problem for each of the small pieces. Now merge all of the piecewise solutions
into a global solution. This strategy is called divide and conquer.Divide and
conquer uses the following steps to make a dispute on an algorithm.
Divide: In this section, the algorithm divides the original problem into a set of
subproblems.Conquer: In this section, the algorithm solves every subproblem
individually.Combine: In this section, the algorithm puts together the solutions of
the subproblems to get the solution to the whole problem./Explain the BFS
algorithm?BFS (Breadth First Search) is a graph traversal algorithm. It starts
traversing the graph from the root node and explores all the neighboring nodes.
It selects the nearest node and visits all the unexplored nodes. The algorithm
follows the same procedure for each of the closest nodes until it reaches the goal
state.AlgorithmStep1: Set status=1 (ready state)Step2: Queue the starting node A
and set its status=2, i.e. (waiting state)Step3: Repeat steps 4 and 5 until the queue
is empty.Step4: Dequeue a node N and process it and set its status=3, i.e.
(processed state)Step5: Queue all the neighbors of N that are in the ready state
(status=1) and set their status =2 (waiting state)
[Stop Loop]Step6: Exit/What is Dijkstra's shortest path
algorithm?Dijkstra's algorithm is an algorithm for finding the shortest path
from a starting node to the target node in a weighted graph. The algorithm makes
a tree of shortest paths from the starting vertex and source vertex to all other
nodes in the graph.Suppose you want to go from home to office in the shortest
possible way. You know some roads are heavily congested and challenging to use
this, means these edges have a large weight. In Dijkstra's algorithm, the shortest
path tree found by the algorithm will try to avoid edges with larger weights./Give
some examples of Divide and Conquer algorithm?Some problems
that use Divide and conquer algorithm to find their solution are listed
below.1.Merge Sort2.Quick Sort3.Binary Search4Strassen's Matrix
Multiplication5Closest pair (points)/What are Greedy algorithms? Give
some example of it.A greedy algorithm is an algorithmic strategy which is
made for the best optimal choice at each sub stage with the goal of this, eventually
leading to a globally optimum solution. This means that the algorithm chooses
the best solution at the moment without regard for consequences.Below is a list
of.algorithms.that.finds.their.solution.with.the.use.of.the.algorithm.\Travelling
Salesman Problem\Prim's Minimal Spanning Tree Algorithm\Kruskal's Minimal
Spanning Tree Algorithm\Dijkstra's Minimal Spanning Tree Algorithm\Graph –
Map.Coloring\Graph-Vertex.Cover\Knapsack.Problem\Job.Scheduling
Problem
What is a linear search?Linear search is used on a group of items. It relies
on the technique of traversing a list from start to end by visiting properties of all
the elements that are found on the way.For example, suppose an array of with
some integer elements. You should find and print the position of all the elements
with their value. Here, the linear search acts in a flow like matching each element
from the beginning of the list to the end of the list with the integer, and if the
condition is `True then printing the position of the element.'
Implementing Linear SearchStep1: Traverse the array using for loop.Step2: In
every iteration, compare the target value with the current value of the
arrayStep3: If the values match, return the current index of the arrayStep4: If the
values do not match, shift on to the next array element.Step5: If no match is found,
return/What is a Binary Search Tree?.Nodes which are less than root will
be in the left subtree..Nodes which are greater than root (i.e., contains more
value) will be right subtree.A binary search tree should not have duplicate
nodes.Both sides subtree (i.e., left and right) also should be a binary search
tree./Write an algorithm to insert a node in the Binary search
tree?Insert node operation is a smooth operation. You need to compare it with
the root node and traverse left (if smaller) or right (if greater) according to the
value of the node to be inserted.Algorithm:.Make the root node as the current
node.If the node to be inserted < root.If it has left child, then traverse left.If it
does not have left child, insert node here.If the node to be inserted > root.If it
has the right child, traverse right.If it does not have the right child, insert node
here./How to count leaf nodes of the binary tree?Algorithm-.If the
node is null (contains null values) then return 0..If encountered leaf node. Left
is null and node Right is null then return 1..Recursively calculate the number of
leaf nodes usingNo. of leaf nodes= no of leaf nodes in left subtree + number of leaf
nodes in the right subtree./How to find all possible words in a board
of.characters.(Boggle.game)?Example\dictionary[]={"Java","Point","Qui
z"};\Array[][]={{'J','T','P',},\{'U', 'A', 'A'},\{'Q','S','V'}};\isWord(str):returns true if str is p
resent in dictionary\else false. Output:Following words of the dictionary are
presentJAVA/Write an algorithm to insert a node in a link
list?Algorithm.Check If the Linked list does not have any value then make the
node as head and return it.Check if the value of the node to be inserted is less
than the value of the head node, then insert the node at the start and make it
head..In a loop, find the appropriate node after which the input node is to be
inserted. To find the just node start from the head, keep forwarding until you
reach a node whose value is greater than the input node. The node just before
is the appropriate node..Insert the node after the proper node found in step 3.
How to delete a node in a given link list? Write an algorithm
and a program?.The function must accept a pointer to the start node as
the first argument and node to be deleted as the second argument, i.e., a
pointer to head node is not globa..The function should not return a pointer to
the head node.The function should not accept pointer to pointer to head
node./Explain how the encryption algorithm works?Encryption is
the technique of converting plaintext into a secret code format it is also called as
"Ciphertext." To convert the text, the algorithm uses a string of bits called as
"keys" for calculations. The larger the key, the higher the number of potential
patterns for Encryption. Most of the algorithm use codes fixed blocks of input
that have a length of about 64 to 128 bits, while some uses stream method for
encryption./What Are The Criteria Of Algorithm Analysis? Time
complexity deals with the quantification of the amount of time taken by a set of
code or algorithm to process or run as a function of the amount of input. In other
words, the time complexity is efficiency or how long a program function takes to
process a given input.Space complexity is the amount of memory used by the
algorithm to execute and produce the result./What are the differences
between stack and Queue?Stack and Queue both are non-primitive
data structure used for storing data elements and are based on some real-world
equivalent.Working principleThe significant difference between stack and
queue is that stack uses LIFO (Last in First Out) method to access and add data
elements whereas Queue uses FIFO (First in first out) method to obtain data
member.StructureIn Stack, the same end is used to store and delete elements,
but in Queue, one end is used for insertion, i.e., rear end and another end is used
for deletion of elements.Number of pointers usedStack uses one pointer
whereas Queue uses two pointers (in the simple case).Operations
performedStack operates as Push and pop while Queue operates as Enqueue
and dequeuer.VariantsStack does not have variants while Queue has variants
like a circular queue, Priority queue, doubly ended Queue.ImplementationThe
stack is simpler while Queue is comparatively complex./What is the
difference between the Singly Linked List and Doubly Linked
List data structure?This is a traditional interview question on the data
structure. The major difference between the singly linked list and the doubly
linked list is the ability to traverse.You cannot traverse back in a singly linked list
because in it a node only points towards the next node and there is no pointer to
the previous node.On the other hand, the doubly linked list allows you to
navigate in both directions in any linked list because it maintains two pointers
towards the next and previous node.
6) Explain the Bubble sort algorithm?
Bubble sort is the simplest sorting algorithm among all sorting algorithm. It
repeatedly works by swapping the adjacent elements if they are in the wrong
order.e.g..(72538) we have this array for sorting..Pass1:

(72538) -> (27538) swap 7 and 2.


(27538) -> (25738) swap 7 and 5.
(25738) -> (25378) swap 7 and 3.
(25378) -> (25378) algorithm does not swap 7 and 8 because 7<8..Pass2:

(25378) -> (25378) algorithm does not swap 2 and 5 because 2<5.
(25378) -> (23578) swap 3 and 5.
(23578) -> (23578) algorithm does not swap 5 and 7 because 5<7.
(23578) -> (23578) algorithm does not swap 7 and 8 because 7<8.

Here, the sorted element is (23578).

You might also like