Você está na página 1de 15

Ques 1: What is an algorithm.

Ans: An algorithm is a procedure used to solve a well defined computational problem.


Ques 2: Give the complexity in terms of ig ! notation for the following algorithmic
e"uations #
$a% &.n'2 ( )n * 2 $b%).2'n * )
Ans. $a% !$n'2%
$b% !$2'n%
Ques +. Arrange the following in increasing order of time complexity #
!$1% , !$2'n% , !$n'2%, !$nlogn%, !$n'+%, !$n%, !$logn%

Ans. !$1%- !$logn%- !$n%- !$nlogn%- !$n'2%- !$n'+%- !$2'n%
Ques .. What do you understand by term ! in ig ! notation #
Ans. !$g$n%% / 0f$n% : there exists positive constants c , n1 such that 1 -/ f$n%-/ cg$n%
for all n2
Ques &. 3how that the solution of 4$n%/4$n52% * 1 is !$lg n%.
Ans. 6sing the iteration method, we substitute the function recursively till we arrive at
4$1%.
i.e 4$n%/4$n52% * 1 / 4$n5.% * 1 * 1 / ....
We get a total of lg$n% iterations
i.e 4$n%/4$1% *lg$n%
4hus the complexity is !$lg n%.
Ques). 3how that the solution to 4$n%/274$$n52%*18% is !$n7$lg n%%.
Ans. 6sing the iteration method, it ta9es lg$n% iterations to reach 4$1%.After final
iteration:
4$n%/$2'lg$n%%7$4$1% * lg$n%718%
4hus the complexity is $2'lg$n%%7$lg n% / !$n7lg$n%%
Ques8. 3olve the recurrence 4$n%/274$s"rt$n%% * 1.
Ans. :et n/2'm,then 4$2'm%/274$2'm52% * 1
;ow let 3$m%/4$2'm%.
/<3$m%/273$m52% *1
4his is the same as 2nd problem.
4hus the complexity is !$m7lg$m%%,but m/lg$n%
4hus the final complexity is !$lg$n%7lg$lg$n%%%
Ques =: >oes the minimum spanning tree of a graph give the shortest distance between
any 2 specified nodes#
Ans: ;o. ?inimal spanning tree assures that the total weight of the tree is 9ept at its
minimum. ut it doesn@t mean that the distance between any two nodes involved in the
minimumAspanning tree is minimum.
Ques B: What is the difference between C3 and >C3#
Ans : C3: 4his can be throught of as being li9e >iD9stra@s algorithm for shortest paths,
but with every edge having the same length. Eowever it is a lot simpler and doesn@t need
any data structures. We Dust 9eep a tree $the breadth first search tree%, a list of nodes to be
added to the tree, and mar9ings $oolean variables% on the vertices to tell whether they
are in the tree or list.
>epth first search is another way of traversing graphs, which is closely related to
preorder traversal of a tree. Fecall that preorder traversal simply visits each node before
its children. Gt is most easy to program as a recursive routine:

Ques 11:Write an algorithm to find the shortest path in Graphs #
Ans: 4he Cloyd(Warshall algorithm compares all possible paths through the graph
between each pair of vertices.
Assume edgeCost$i,D% returns the cost of the edge from i to D $infinity if there is none%, n is
the number of vertices, and edgeCost$i,i% / 1.
Algorithm
int pathHIHIJ 55 a 2A> matrix.
55 At each step, pathHiIHjI is the $cost of the% shortest path
55 from i to j using intermediate vertices $1.. k A1%.
55 Kach pathHiIHDI is initialiLed to edgeCost $i,D%
55 or M if there is no edge between i and j.
procedure FloydWarshall $%
for 9 in 1..n
for each pair $i,D% in 01,..,n2x01,..,n2
pathHiIHjI / min $ pathHiIHjI, pathHiIHkI*pathHkIHjI %J
Ques 11: Write a single source shortest path algorithm and its time complexity#
Ans : >iD9stra@s algorithm solves the singleAsource shortestApath problem when all edges
have nonAnegative weights. Gt is a greedy algorithm and similar to Nrim@s algorithm.
Algorithm starts at the source vertex, s, it grows a tree, 4, that ultimately spans all
vertices reachable from 3. Oertices are added to 4 in order of distance i.e., first 3, then the
vertex closest to 3, then the next closest, and so on. Collowing implementation assumes
that graph G is represented by adDacency lists.

>GPQ34FA $G, w, s%
G;G4GA:GRK 3G;G:KA3!6FSK $G, s%
3 T 0 2 55 3 will ultimately contains vertices of final shortestApath weights from s
GnitialiLe priority "ueue Q i.e., Q T OHGI
while priority "ueue Q is not empty do
u T KU4FAS4V?G;$Q% 55 Null out new vertex
3 T 3 W 0u2
55 Nerform relaxation for each vertex v adDacent to u
for each vertex v in AdDHuI do
Felax $u, v, w%

Analysis
:i9e Nrim@s algorithm, >iD9stra@s algorithm runs in !$XKXlgXOX% time.
Ques 12:>oes diD9stra@s algorithm for shortest path provide the optimal solution #
Ans : Yes, diD9stra@s algorithm for shortest path provide the optimal solution.
4o find the shortest path between points, the weight or length of a path is calculated as
the sum of the weights of the edges in the path. A path is a shortest path is there is no path
from x to y with lower weight. >iD9stra@s algorithm finds the shortest path from x to y in
order of increasing distance from x. 4hat is, it chooses the first minimum edge, stores this
value and adds the next minimum value from the next edge it selects. Gt starts out at one
vertex and branches out by selecting certain edges that lead to new vertices. Gt is similar
to the minimum spanning tree algorithm, in that it is ZgreedyZ, always choosing the
closest edge in hopes of an optimal solution.
Ques 1+:Kxplain Nrim[s Algorithm .
Ans: :i9e Qrus9al@s algorithm, Nrim@s algorithm is based on a generic ?34 algorithm.
4he main idea of Nrim@s algorithm is similar to that of >iD9stra@s algorithm for finding
shortest path in a given graph. Nrim@s algorithm has the property that the edges in the set
A always form a single tree. We begin with some vertex v in a given graph G /$O, K%,
defining the initial set of vertices A. 4hen, in each iteration, we choose a minimumA
weight edge $u, v%, connecting a vertex v in the set A to the vertex u outside of set A.
4hen vertex u is brought in to A. 4his process is repeated until a spanning tree is formed.
:i9e Qrus9al@s algorithm, here too, the important fact about ?34s is we always choose
the smallestAweight edge Doining a vertex inside set A to the one outside the set A. 4he
implication of this fact is that it adds only edges that are safe for AJ therefore when the
algorithm terminates, the edges in set A form a ?34.

Algorithm

?34VNFG? $G, w, v%
1. Q T OHGI
2. for each u in Q do
+. 9ey HuI T M
.. 9ey HrI T 1
&. \HrI T ;Gl
). while "ueue is not empty do
8. u T KU4FAS4V?G; $Q%
=. for each v in AdDHuI do
B. if v is in Q and w$u, v% - 9ey HvI
11. then \HvI T w$u, v%
11. 9ey HvI T w$u, v%

Ques 1. :What is the difference between binary searching and Cibonacci search#
Ans: inary 3earch: inary search is the process of locating an element in a sorted list.
4he search starts by dividing the list into two parts. 4he algorithm compares the median
value. Gf the search element is less than the median value, the top list only will be
searched, after finding the middle element of that list. 4he process continues until the
element is found or the search in the top list is completed. 4he same process is continued
for the bottom list, until the element is found or the search in the bottom list is completed.
Gf an element is found that must be the median value.
Cibonacci 3earch: Cibonacci search is a process of searching a sorted array by utiliLing
divide and con"uer algorithm. Cibonacci search examines locations whose addresses have
lower dispersion. When the search element has nonAuniform access memory storage, the
Cibonacci search algorithm reduces the average time needed for accessing a storage
location.
Ques 1&: Kxplain the bubble sort algorithm.
Ans: ubble sort algorithm is used for sorting a list. Gt ma9es use of a temporary variable
for swapping. Gt compares two numbers at a time and swaps them if they are in wrong
order. 4his process is repeated until no swapping is needed. 4he algorithm is very
inefficient if the list is long.
K.g. :ist: A 8 . & +
1. 8 and . are compared
2. 3ince . - 8, . is stored in a temporary variable.
+. the content of 8 is now stored in the variable which was holding .
.. ;ow, the content of temporary variable and the variable previously holding 8 are
swapped.
Ques 1): Kxplain Quic9 3ort
Ans: 4he "uic9 sort algorithm is of the divide and con"uer type. 4hat means it wor9s by
reducing a sorting problem into several easier sorting problems and solving each of them.
A dividing value is chosen from the input data, and the data is partitioned into three sets:
elements that belong before the dividing value, the value itself, and elements that come
after the dividing value. 4he partitioning is performed by exchanging elements that are in
the first set but belong in the third with elements that are in the third set but belong in the
first Klements that are e"ual to the dividing element can be put in any of the three sets the
algorithm will still wor9 properly.
Ques 18: Kxplain ?erge 3ort
Ans: 4he merge sort is a divide and con"uer sort as well. Gt wor9s by considering the data
to be sorted as a se"uence of alreadyAsorted lists $in the worst case, each list is one
element long%. AdDacent sorted lists are merged into larger sorted lists until there is a
single sorted list containing all the elements. 4he merge sort is good at sorting lists and
other data structures that are not in arrays, and it can be used to sort things that don@t fit
into memory. Gt also can be implemented as a stable sort.
Ques 1=:3ort the given values using Quic9 3ort#
)& 81 8& =1 =& )1 && &1 .&
Ans:
3orting ta9es place from the pivot value, which is the first value of the given
elements, this is mar9ed bold. 4he values at the left pointer and right pointer are
indicated using : and F respectively.
)& 81
:
8& =1 =& )1 && &1 .&
F
3ince pivot is not yet changed the same process is continued after interchanging
the values at : and F positions
)& .& 8&
:
=1 =& )1 && &1
F
81
)& .& &1 =1
:
=& )1 &&
F
8& 81
)& .& &1 && =&
:
)1
F
=1 8& 81
)& .& &1 && )1
F
=&
:
=1 8& 81
When the : and F pointers cross each other the pivot value is interchanged with the value
at right pointer. Gf the pivot is changed it means that the pivot has occupied its original
position in the sorted order $shown in bold italics% and hence two different arrays are
formed, one from start of the original array to the pivot positionA1 and the other from
pivot position*1 to end.
)1
:
.& &1 &&
F
)& =&
:
=1 8& 81
F
&&
:
& .& &1
F
)1 )& 81
F
=1
:
8& =&
&1
:
.&
F
&& )1 )& 81 =1
:
8&
F
=&
Gn the next pass we get the sorted form of the array.
.& &1 && )1 )& 81 8& =1 =&
Ques 1B: What is difference between ubble 3ort and Quic9 sort#
Ans: ubble 3ort: 4he simplest sorting algorithm. Gt involves the sorting the list in a
repetitive fashion. Gt compares two adDacent elements in the list, and swaps them if they
are not in the designated order. Gt continues until there are no swaps needed. 4his is the
signal for the list that is sorted. Gt is also called as comparison sort as it uses comparisons.
Quic9 3ort: 4he best sorting algorithm which implements the ]divide and con"uer[
concept. Gt first divides the list into two parts by pic9ing an element a [pivot[. Gt then
arranges the elements those are smaller than pivot into one sub list and the elements those
are greater than pivot into one sub list by 9eeping the pivot in its original place.
Ques 21. What are elements of dynamic programming#

Ans. Klements of >ynamic Nrogramming
^ !ptimal subAstructure $Nrinciple of !ptimality%
an optimal solution to the problem contains within it optimal
solutions to subAproblems.
^ !verlapping subproblems
there exist some places where we solve the same subproblem
more than once.
Ques 21. What is a greedy algorithm#
Ans. A greedy algorithm is an algorithm that follows the problem solving heuristic of
ma9ing the locally optimal choice at each stage

with the hope of finding a global
optimum. !n some problems, a greedy strategy need not produce an optimal solution, but
nonetheless a greedy heuristic may yield locally optimal solutions that approximate a
global optimal solution.
Ques22. What is difference between dynamic programming and greedy algorithm#
XAns. >ynamic Nrogramming
ottom up $while Greedy is topAdown%
^ >ynamic programming can be over9illJ greedy
algorithms tend to be easier to code
XQues 2+. What is ?atrix Shain ?ultiplication Nroblem#
Ans. 3uppose we have a se"uence or chain A1, A2, _, An of n matrices to be multiplied.
4here are many possible ways $parenthesiLations% to compute the product
Kxample: consider the chain A1, A2, A+,A.of . matrices
:et us compute the product A1A2A+A.
4here are & possible ways:
$A1 $A2 $A+ A.%%%
$A1 $$A2 A+% A.%%
$$A1 A2%$ A+ A.%%
$$A1 $A2 A+%% A.%
$$$A1 A2% A+% A.%
?atrixAchain multiplication problem states that given a chain A1, A2, _, An of n matrices,
where for i/1, 2, _, n, matrix Ai has dimension pi-1 pi. NarenthesiLe the product A1, A2,
_, An such that the total number of scalar multiplications is minimiLed.
Ques 2.. Given the following 2 strings 3 and 4, find their longest common subse"uence.
3 / AAR>S
4 / ASA>
Ans. A S A >
A 1 1 1 1 1 1
1 1 1 2 2 2
A 1 2 2 2 + +
R 1 2 2 2 + +
> 1 2 2 2 + .
S 1 2 + + + .
4hus :S3 is ..
Ques 2&. What is the time complexity for matrix multiplication and 3trassen[s ?atrix
?ultiplication#
Ans. ?atrix ?ultiplication/ ( (n n
+ +
% %
3trassen[s ?atrix ?ultiplication: ( (n n
2.=1 2.=1
% %
Ques 2). What is activity selection problem# Ques 2). What is activity selection problem#
Ans. 3cheduling a resource among several competing activities Ans. 3cheduling a resource among several competing activities
^ ^ >efinition >efinition
( ( 3/01, 2,_, n2 ( activities that wish to use a resource and a finish time fi, 3/01, 2,_, n2 ( activities that wish to use a resource and a finish time fi,
where si where si fi fi
( ( Gf selected, activity i ta9es place during the halfAopen interval Hsi, fi% Gf selected, activity i ta9es place during the halfAopen interval Hsi, fi%
( ( Activities i and D are compatible if Hsi, fi% and HsD, fD% don[t overlap Activities i and D are compatible if Hsi, fi% and HsD, fD% don[t overlap
( ( 4he activityAselection problem is to select a maximumAsiLe set of mutually 4he activityAselection problem is to select a maximumAsiLe set of mutually
compatible activities compatible activities
Ques28. Kxplain 3trassen[s ?atrix ?ultiplication.
Ans. Gt uses only 8 scalar multiplications to multiply two 2x2 matrices. Gt divides each of
A, and S matrices into four n52 x n52 matrices and rewriting e"uation S/A as:
r s / a b e f
t u c d g h
r/ N&*N.AN2*N)
s/N1*N2
t/N+*N.
u/N&*N1AN+AN8
Where:
N1/a$fAh%
N2/$a*b%h
N+/$c*d%e
N./d$gAe%
N&/$a*d%$e*h%
N)/$bAd%$g*h%
N8/$aAc%$e*f%
Ques 2=. Write the algorithm for 4opological 3ort.
Ans. int topological!rder4raversal$ %0
int numOisitedOertices / 1J
while$there are more vertices to be visited%0
if$there is no vertex with inAdegree 1%
brea9J
else0
select a vertex v that has inAdegree 1J
visit vJ
numOisitedOertices**J
delete v and all its emanating edgesJ
2
2
return numOisitedOerticesJ
2
Ques 2B.Sompare the running time for ;a`ve 3tring ?atching and Qnuth ?orris Nratt
algorithm for string ?atching.
Ans. Funning time for ;a`ve 3tring ?atching : !$$nAm*1% m%
Funning time for Q?N ?atcher: !$$nAm*1% m%
Ques +1. What is optimal binary search tree#
Ans. !34 is one special 9ind of advanced tree. Gt focus on how to reduce the cost of the
search of the 34. Gt needs + tables to record probabilities, cost, and root.
Gt has n 9eys $representation 91,92,_,9n% in sorted order $so that 91-92-_-9n%, and we
wish to build a binary search tree from these 9eys. Cor each 9i ,we have a probability pi
that a search will be for 9i.
Gn contrast of, some searches may be for values not in 9i, and so we also have n*1
adummy 9eysb d1,d1,_,dn representating not in 9i.
Gn particular, d1 represents all values less than 91, and dn represents all values greater
than 9n, and for i/1,2,_,nA1, the dummy 9ey di represents all values between 9i and
9i*1.
Ques +1. What is the difference between divide and con"uer and dynamic programming#
Ans. oth solve problem by dividing prob into subAproblems
$1%but in >ynamic programming the sub problems are not independent where as in divide
and con"uer the sub problems are independent of each other
$2%>ynamic programming solves the sub problem only once and then stores it in table
whereas divide and con"uer does more wor9 on the sub problems and hence has more
time consumption.
Ques +2. Sonsider an array with numbers & 1 . 2 = and sort using bubble sort.
Ans. Cirst Nass:
$ & 1 . 2 = % $ 1 & . 2 = %, Eere, algorithm compares the first two elements, and swaps
them.
$ 1 & . 2 = % $ 1 . & 2 = %, 3wap since & < .
$ 1 . & 2 = % $ 1 . 2 & = %, 3wap since & < 2
$ 1 . 2 & = % $ 1 . 2 & = %, ;ow, since these elements are already in order $= < &%,
algorithm does not swap them.
3econd Nass:
$ 1 . 2 & = % $ 1 . 2 & = %
$ 1 . 2 & = % $ 1 2 . & = %, 3wap since . < 2
$ 1 2 . & = % $ 1 2 . & = %
$ 1 2 . & = % $ 1 2 . & = %
;ow, the array is already sorted, but our algorithm does not 9now if it is completed. 4he
algorithm needs one whole pass without any swap to 9now it is sorted.
4hird Nass:
$ 1 2 . & = % $ 1 2 . & = %
$ 1 2 . & = % $ 1 2 . & = %
$ 1 2 . & = % $ 1 2 . & = %
$ 1 2 . & = % $ 1 2 . & = %
Ques ++. Collowing are 8 activities with their respective deadlines and penalities.
ai 1 2 + . & ) 8
di . 2 . + 1 . )
wi 81 )1 &1 .1 +1 21 11
3olve using the tas9 scheduling such that penalty is minimiLed.
Ans. 4he solution to this problem is 0a2,a.,a1,a+,a8,a&,a)2
penality , w&*w)/&1
Ques +.. What is est Cirst 3earch#
Ans. estAfirst search is a search algorithm which explores a graph by expanding the
most promising node chosen according to a specified rule.
Kfficient selection of the current best candidate for extension is typically implemented
using a priority "ueue.
Ques +&. What is the difference between >C3 and C3.
Ans. >C3 $>epth Cirst 3earch% and C3 $readth Cirst 3earch% are search algorithms
used for graphs and trees. When you have an ordered tree or graph, li9e a 34, it[s "uite
easy to search the data structure to find the node that you want. ut, when given an
unordered tree or graph, the C3 and >C3 search algorithms can come in handy to find
what you[re loo9ing for. 4he decision to choose one over the other should be based on the
type of data that one is dealing with.
Gn a breadth first search, you start at the root node, and then scan each node in the first
level starting from the leftmost node, moving towards the right. 4hen you continue
scanning the second level $starting from the left% and the third level, and so on until
you[ve scanned all the nodes, or until you find the actual node that you were searching
for. Gn a C3, when traversing one level, we need some way of 9nowing which nodes to
traverse once we get to the next level. 4he way this is done is by storing the pointers to a
level[s child nodes while searching that level. 4he pointers are stored in CGC! $CirstAGnA
CirstA!ut% "ueue. 4his, in turn, means that C3 uses a large amount of memory because
we have to store the pointers.
Ques +). What is Qnapsac9 problem#
Ans. 4he 9napsac9 problem or ruc9sac9 problem is a problem in combinatorial
optimiLation: Given a set of items, each with a weight and a value, determine the count of
each item to include in a collection so that the total weight is less than or e"ual to a given
limit and the total value is as large as possible. Gt derives its name from the problem faced
by someone who is constrained by a fixedAsiLe 9napsac9 and must fill it with the most
useful items.
Gn the following, we have n 9inds of items, 1 through n. Kach 9ind of item i has a value vi
and a weight wi. We usually assume that all values and weights are nonnegative. 4o
simplify the representation, we can also assume that the items are listed in increasing
order of weight. 4he maximum weight that we can carry in the bag is W.
4he most common formulation of the problem is the 1A1 9napsac9 problem, which
restricts the number xi of copies of each 9ind of item to Lero or one. ?athematically the
1A1A9napsac9 problem can be formulated as:
maximiLe
subDect to
4he bounded 9napsac9 problem restricts the number x
i
of copies of each 9ind of item to a
maximum integer value c
i
. ?athematically the bounded 9napsac9 problem can be
formulated as:
maximiLe
subDect to
4he unbounded 9napsac9 problem $6QN% places no upper bound on the number of copies
of each 9ind of item.
!f particular interest is the special case of the problem with these properties:
it is a decision problem,
it is a 1A1 problem,
for each 9ind of item, the weight e"uals the value: w
i
/ v
i
.
Ques +8. What is the dynamic programmic solution to Qnapsac9 problem#
Ans. Gf all weights $ % are nonnegative integers, the 9napsac9 problem
can be solved in pseudoApolynomial time using dynamic programming. 4he following
describes a dynamic programming solution for the unbounded 9napsac9 problem.
4o simplify things, assume all weights are strictly positive $wi < 1%. We wish to maximiLe
total value subDect to the constraint that total weight is less than or e"ual to W. 4hen for
each w c W, define m[w] to be the maximum value that can be attained with total weight
less than or e"ual to w. m[W] then is the solution to the problem.
!bserve that m[w] has the following properties:
$the sum of Lero items, i.e., the summation of the empty set%

where v
i
is the value of the iAth 9ind of item.
1A1 9napsac9 problem
A similar dynamic programming solution for the -1 knapsack problem also runs in
pseudoApolynomial time. As above, assume are strictly positive
integers. >efine mHi,wI to be the maximum value that can be attained with weight less
than or e"ual to w using items up to i.
We can define mHi,wI recursively as follows:

if $the new item is more than the current


weight limit%
if .
Ques +=. What is 4ower of Eanoi problem#
Ans. 4he 4ower of Eanoi is a mathematical game or puLLle. Gt consists of three rods, and
a number of dis9s of different siLes which can slide onto any rod. 4he puLLle starts with
the dis9s in a neat stac9 in ascending order of siLe on one rod, the smallest at the top, thus
ma9ing a conical shape.
4he obDective of the puLLle is to move the entire stac9 to another rod, obeying the
following rules:
!nly one dis9 may be moved at a time.
Kach move consists of ta9ing the upper dis9 from one of the rods and sliding it
onto another rod, on top of the other dis9s that may already be present on that rod.
;o dis9 may be placed on top of a smaller dis9.
4he puLLle can be played with any number of dis9s, although many toy versions have
around seven to nine of them. 4he game seems impossible to many novices, yet is
solvable with a simple algorithm. 4he number of moves re"uired to solve a 4ower of
Eanoi puLLle is 2
n
A1, where n is the number of dis9s.
Ques +B. 3ort the following using 3election sort:
). 2& 12 22 11
Ans. ). 2& 12 22 11
11 2& 12 22 ).
11 12 2& 22 ).
11 12 22 2& ).
11 12 22 2& ).
Ques .1. What is shell sort#
Ans. 3hell sort, also 9nown as 3hell sort or 3hell@s method is an inAplace comparison sort.
Gt generaliLes an exchanging sort, such as insertion or bubble sort, by allowing the
comparison and exchange of elements that lie far apart

. Gts first version was published by
>onald 3hell in 1B&B .4he running time of 3hell sort is heavily dependent on the gap
se"uence it uses. Cor many practical variants, determining their time complexity remains
an open problem.
3hell sort is a multiApass algorithm. Kach pass is an insertion sort of the se"uences
consisting of every hAth element for a fixed gap h $also 9nown as the increment%. 4his is
referred to as hAsorting.
Ques .1. Write the algorithm for counting sort.
Ans. @@@ allocate an array SountH1..9I J initialiLe each array cell to Lero J 4EK; @@@
for each input item x:
SountH9ey$x%I / SountH9ey$x%I * 1
total / 1
for i / 1, 1, ... 9:
c / SountHiI
SountHiI / total
total / total * c

@@@ allocate an output array !utputH1..nA1I J 4EK; @@@
for each input item x:
store x in !utputHSountH9ey$x%II
SountH9ey$x%I / SountH9ey$x%I * 1
return !utput
Ques .2. What is the difference between "uic9 sort and randomiLed "uic9 sort#
Ans. Gn "uic9 sort the first element in the array is chosen as the pivot but in randomiLed
"uic9 sort any number in the array is chosen as the pivot.
Ques .+. What is difference between ubble sort and Kxchange sort#
Ans. 4he difference between these two sorts is the manner in which they compare the
elements. 4he exchange sort compares the first element with each following element of
the array, ma9ing any necessary swaps.

Ques ... 3ort the following using Kxchange sort in descending order.
=. )B 8) =) B. B1
Array at beginning:=. )B 8) =) B. B1
After Nass d1: B. )B 8) =. =) B1
After Nass d2: B. B1 )B 8) =. =)
After Nass d+: B. B1 =) )B 8) =.
After Nass d.: B. B1 =) =. )B 8)
After Nass d& B. B1 =) =. 8) )B
Ques .&. >iscuss the best case and worst case running time of insertion sort.
Ans. 4he best case input is an array that is already sorted. Gn this case insertion sort has a
linear running time $i.e., e$n%%. >uring each iteration, the first remaining element of the
input is only compared with the rightAmost element of the sorted subsection of the array.
4he worst case input is an array sorted in reverse order. Gn this case every iteration of the
inner loop will scan and shift the entire sorted subsection of the array before inserting the
next element. Cor this case insertion sort has a "uadratic running time $i.e., !$n
2
%%.

Você também pode gostar