is stored into this array
He n array. Data i Y at specip
fn table data structure aaa funetion hiashes (converts) a number jn 2 i
‘A ha
by a hash function.
generated by a smaller range. | Search is a method where the search begins ay
into a number in ss i t
f Linear search: ee ae or ft ght the Search begins fom
jer ‘
2 Ahas!
4 in an ordered list or an unordeted list pay
cole Ss such as linked Fists or files with van
i cessed $e ; ! S with varia
fists that must e — the average performance can be improved by Biving up stig
: toons ct eater than the unmatched target value, rather than examining i
element i
Lae i d list is divided into two
i + In Binary Search the entire sorted | n ae
con Oa item ath the mid element of the list and then restrict Our attention
the fyst or second half ofthe list depending on whether the input item comes left or
the mid-element. In this way we reduce the length of the list to be searched by ha
Hashing: In hash tables, there is always a possibility that two data elements will
same integer value. When this happens, a collision occurs i.e. two data members ty
thelist, scans the el
desired record is found.
This type of searching
try today
ds to deal with such situato
ZL the same place in the hash table array. There are nletho«
Open Addressing and Chaining ae
‘* Bubble sort: Given an array of unsorted elements, Bubble sort performs a sorting’
on the first two adjacent elements in the array, then between the second & thitd, then
third & fourth & so on, :
* Insertion sort: In insertion sort data is sorted data set by identifying an element that i
order eelative to the elements around it. It removes that element from the list, shifngd
elements up one place. a
Finally it places the int i
Fr eumpe wie lg ei et lation ue
tight, looking forthe frst eaed ther y S, Players will often scan their.cards IX
card that is out of place. if the first three cards of a pI
upon getting to the 2, desi .
typically removes ia Pps 2 Place it before the 4 and the 5. In that cis6
places the 2 int the tr sel : a tis, shits the 4 and the 5 one spot to the righh
© Quick sort: In Qu; eee “ .
elements to the lef of the n a array) and perform a sorting in such a mantel
a vo ; :
/'. ier to oa
In this met! *W sub arrays, 4
nearly equal as posible ang yes GE the aray or list into two sub aay
into another sub arra Sort them s js ate:
/ . ys, eparately. Then the sub-arrays
Heap sort: A heap takes the form of
« /Orm of a
in the root, binary tree with the feature
Dependinig upon this féature the
DSA-110 i
minimum element is py
BEBE
heap ‘
taken
the he:
4. The rat
a) loac
Answer: (
2. Which ¢
a) Aveo
c) Mak
Answer: (|
3, Stability
‘a) So
b) We
c) So
d) No
Answer: (a
4. Which of
a) O(n)
Answer: (b
5. The Line:
a) Primi
©) Overt
Answer: (a)
Scanned with CamScannerDAT: &Al
ap of min-heap respectively. After the h
nea? Sc from the tree and the heap struc
wea i MP
ee uetion ‘the elements from the root are
e is reconstructed. This process continues until
Multiple Choice Type Questions
«the ratio of the number of items in a hash table, to the table size is called the
[WBUT 2007, 2009, 2016]
4) oad factor b) item factor ¢) balanced factor _d) all of these
answer (a)
nich of the following is not a requirement of good hashing function?
avoid collision b) Reduce the storage space
) Make faster retrieval d) None of these [WBUT 2008, 2015]
answer: (D)
subilty of Sorting Algorithm is important for
38) Sorting records on the basis of multiple keys paged
}) Worst case performance of sorting algorithm
{) Sorting alpha numeric keys as they are likely to be the same
@) None of these
Answer (a)
AWhich of the following is the best time for ai algorithm? [WBUT 2007]
a) O(n) b) O(log2 n) ¢) O(2n) “ * d) O(n log2 n)
Answer: (b)
The Linear Probing Technique for collision resolution can lead to / [WBUT 2003]
2)Primary clustering b) Secondary clustering,
«) Overflow d) Efficiency storage utilization
Aaswer: (a)
{The fastest sorting algorithm for an almost already sorted array is [WBUT 2009]
) quick sort b) merge sort ¢) selection sort, _d) insertion sort
Answer: (a)
he tr ii hi [WBUT 2009]
BOR ee on)” search's) Ollogn) €) O(n tog n)
Iswer: (¢)
‘Thetest case time complexity of Bubble sort technique is [WBUT 2010]
4) 0(n) b) o(n’) ¢) O(nlog. n) a) O(log”)
er (a)
‘ psA-li1
Scanned with CamScanner‘pereee a
u
POPULAR PUBLICATIONS rocodures is the slowest? Iweur
q rt 4) Bi
orting c) Merge 5° ub 9)
ich of the following S07 co
aah nn
- ‘ lements of g
“Answer: (4) niques lists the el of
following traversal tee! DWBUT 2045, 1, Binary S
" 40, Which of the Tern der? c) Inorder 4) None of 20-1) divide
1 search tree in 502°") post-order : 3) heurist
a) pre-o! 3 (b)
: wer!
i ‘Answer: (C) ; a weur 5, Ans}
it arch cannot be used in linked lists. UT 2 1, Merge sof
41. Binary se b) False 2) divide :
a ) hourist
Answer: (b) i £ ¢ ora)
algorithm uses.....--data structure | (WEUT 2 Answer
42, Breadth-first-search algorit ) binary tree ) none of iy
a) stack b) quel 22. The prerec
Answer: (b) a) unsorte
pi iti is- BU c) descenc
43. The best case complexity of insertion sort is [WBUT 264 ate
alr) b)O(rloesn) OC") 4) O(n) ©
Answer: (d) .
14. Which of the following is not related to hashing? [WBUT
a) Synonyms —_b) Collision c) Balance 4) Load face
Answer: (c)
4. Explain the.
Answer:
A sequential se
item, and so on
occur in the gro
A binary search
the array to det
strategy on ont
15. A machine needs a minimum of 100sec to sort 1000 names by quick sort Tk
minimum time needed to sort 100 names will be approximately BUT:
a) 727sec — b) 11.2sec c) 50.2 sec d)6.7 sec
‘Answer: (d)
26. What will be the time complexity for selection sort to ‘sort an. arr
elements? le benefit of |
a) O(log n) «© clement
baswen ch i) ©) O(n) simple aera
Sf
17. The best sorting techni Worthwhit re
2) Selection orto) ace pihen the data is almost sorted is Binary gue fF S
Answer: (d) esort = ¢) Quick sort Middie terme is
18. Which of the followin,
2 What:
a) Quadratic provi’ © hash function? tis hashi
¢) open addressing b) chainin Refine Hasp,
Answer: (a)! 4) folding 8 wet % conn
lin Linea
ar F
DSA-112
Scanned with CamScannerTA! RI
e namber of swapping neeg, d . *GORITHM
#2 Ming order using bubble sort ie) °° SOP numby i
ll Sortis —~ ers 8, 22, 7, 9, 31, 1
oe byt wi BUT 204
set ( ) : me
nary search uses
ppBintyide and redi
idivide and reduce strategy
a) divids by divi [WBUT 2014]
jyheuristic search ivide and conquer
) : 4) both (a) and c r strategy
Me
2) divide and conquer strategy
¢)heuristic search
answer
b) backtracking approach tt)
4) greedy approach
a. The prerequisite condition of Binary search is re [wBuT 2017]
ajunsorted array iy
é)descending order array 7 Steen order array
answer: ()
Short Answer ye Questions
{,fxplain the advantages of binary search over sequential search.
: [WBUT 2007, 2013]
Answer: ; ®
Asequential search of either a list, an array, or a chain looks at the first item, the second
itm, and so on until it either finds a particular item or determines that the item does not
‘curin the group. Average case of sequential searsh is O(n)
Atinary search of an array requires that the array be sorted. It looks first at the middle of
‘earay to determine in which half the desired item. can occur. The search repeats this
Sntegy on only this half of the array. e
Tetenefit of binary search over linear sear
WW ements. For smaller lists linear search
‘Tol increment compared with the divisions n
= for large lists binary search is very mu
hvhile for small lists.
search is. not appropriate, for Hin!
ch becomes significant for lists over about
may be faster because of the speed of the
eeded in binary search.
ich faster than linear searcl
ch, but is not
ked list structures (no random access for the
"le erm),
‘ma ut 2007, 2012, 2044, 2017]
| hi hashing? A msi :
ee eres
lashit :
we calsign? sn biartle. [WweUT 20071 :
Linear Probing & Quadratic Probing wit
psAa-113.-
Scanned with CamScannerBLICATIO
oR, lision resoluti
Je the co on ac
guitable exam! wee me
Defino ‘Hashing’. Explain Wi sdressing: ;
"om retion soveme citing one exernle,
sion (Wet ny
using linear probing wit!
Define Hashing. Explain one col
oR, tweur ay
Write two hash functions
Answer:
ra
Hashing is a meth
delete, and search for records ba
these operations can be performes
typically looks at only one or (0
jg far better than the O(log n) averaBe
of n records, or the O(log 1) avenge ,
tree. However, even though hashing |S
difficult to implement properly. Designers need to
cords from a database. It lets YoU ing
value. When properly implemen a
a saree, Infact, a propery tuned hash sy
4 inca foreach ‘search. insert, or delete operation
rs quired to do a binary SEACH ON A sorted an,
ost reared to d0 an operation on a Binty seg
earn a very simpte idea, itis surprising
pay careful attention to all of
1g and retrieving Te
seed on a search Key
1od for storiny
ved with implementing a hash system : /
‘iach System stores mprords in an array called a hash table, which we will call i
's 4 putation on search key K in a way that is intended Insert k
+ 20
ming a com h y that
to identify the position in HTT that contains the record with key K. The function that dog
tae ation iy called the hash function, and is usually denoted by the letter h. Sit
ever order satisfies the needs of thy
hashing schemes place records in the table in what der
ase elation, reeords are not ordered by value. A position in the hash table is aa
known a¢ a slot. The number of slots in hash table HT will be denoted by the variable
with slots numbered from 0 to M- 1.
Hashing works by perforn
- 30
+ 20
- 13
* 25
* 24
+ 10
2” Part:
4 collision between two keys K & K* occurs when both have to be stored in the table& * 9n
both hash to the same address in the table.
: The figure |
3" Part:
Open addressing: It is a general collision resolution scheme for a hash table. Incase of
collision, other positions of the hash table are checked (a probe sequence) until an emply
position is found.
The different types of Open addressing scheme includes
a) Linear Probing (Sequential Probing)
b) Quadratic Probing
) Double Hashing (Re Hashing)
‘ica’ arate ‘
de as a et "solving hash collisions of values of hash functions
s 2 h table for a free location. This i ished win
ent th ion. Thi shed use
pane arith as : Starting value and one as an interval Wie soci Z
ihmeti. The second valu, which isthe same for all keys and kno"? =
DSA-114
Scanned with CamScanner,. is repeatedly added to
‘i th :
H d. Start
at is traverse arts Vale
ol action for the rehashin, Until
Sche i af
TT 2grge) | te ey)=(MHl) % ky Folly, i "SE SPaCe is found, or the entire
3 este. WE AVE a hash table hy "
- fore yed were integers, To jinn, st Could ag,
UL 2043) S09, Ianother input [qo 27 We use jmMedate § informati
} i ; occur hash mation, and
UT 204 oly occur. In this event, the need e 2°d we km e)™ 27 9% dag, pp the data to
Ty) nd (Key )= (1841) % Gus SEE 10 rehash iT that 18 9% 9a" Therefore, 27 is
serra 1. Since | jg fia Needed. Using ha 0, then a collision
Y, 18 lear probit
oud arti probing: 7S ean be stored ini ne ME have
lemented, er to prevent collision we use quadrati
sh system | "jy quadratic probing, — "© Probing scheme,
tion. This We-sat from the original hash locaton ; :
red aray || ratoction is occupied, we check the location sc.
wy search | "ye wrap around from the last table location tye 2S is,
rbrisingly | «Vt fe the following example first table location if necessary.
all of the | MO ies 11 (02.10) .
call Her. | Hash Function: Go) = x mod 11
: | insert keys (20, 30,2,13,25,24,10,9);
s intended Wes 5
1 that does oe
rh. Since | + 30mod II
+ mod 11 =2
+ 3mod 11 =2 > 2412
+ 25mod 11 =3 > 3+1
+ 24 mod 11 =2 > 2417, 2426 i
+ 10mod 11 = 10 is Se ;
* 9mod I
=9D 9417, 942? mod 11, >
943? mod 11 =7
JTefigure below shows the corresponding entries in the hash table.
che table &
|
in case of
0
A
an empty 2
+3[ 8
[25 |
5)
5] 24 |
79
unction’ . | 30 |
using, 130 |
Sales 9120 |
ye 10| 10
nown a
g psa-115
Scanned with CamScannerEE yp
IN is "
POPULAR PUBLICATIONS y for quick sort is O(nlogn) for input g;
-e time complexit Iweut 200m
3. Prove that, the best cas'
ofn.
‘Answer:
The analysis ee)
» PON) + TU-LB) + TU! neti v
neh 7 TUL). and T(UB-S) denote Or sively. Note ace a the | = Partition
left subtable, and sort the ae he hh ‘at each invorati a Ne oc
af cast .
En eae m0 8 th one shen the given key set ig siege
curren a uch a situation, for exam i
LB or J = UB).
a js ming J = LB, then becomes
“The worst case time analysis 2854
Tw = P(N) + TWO) + TW(N-1)
=ctN+TwN-l)
= c#N + c*(N-1) + TW(N-2)
wc#N + c#(N-1) + o*(N-2) FT
K_ SORT is given BY ]
on mes to partition the given table, sony /
.
le, occurs
doeumn flag.
)
5. “Binary sea
the validity of
Answers
The statement i
however it wou
Binary search ¢
element in the
saying array[mi
The same cann
value of the mi
value of any no
One solution to
search is to hay
the middle. De
the linked list. ¢
w(N-3),
c* = O(N? Sioned i ee
Tees eee ae when the table is always partitioned in half, that is, }=
((LB+UB)?J. The analysis becomes:
Tb = P(N) + 2TO(N/2)
= c*N + 2Tb(N/2)
c*N + 2e(N/2) + 4TO(N/A)
+N + 2c(N/2) + de(N/A) + STO(N/8)
= (log2N)*c*N + 2log2N*TO(1)
= O(Nlog2N) 8. Draw a minit
; : 12, 14,
4. Give an algorithm to search for an element in an array using binary search. Now do the i
weut 7 | the insertion
' nsw
What is the precondition of performing binary search in an array? Write the Bina] J ys poe?
Search algorithm. [wut 201 The ane
'© Steps are as
Answer:
Let us consider an array A of size N = 10, Th ii ight i
1 . The let
neo naa (NEED ft index and right index are’
int bin_search(int af},
t 7
int left = 0
right =n - 1;
int flag
int mid
int n, int item)
Scanned with CamScanner(left <= right ;
pile Vode 84 DATA STRUCTURE & ALGORITHM
’ 422 tere
(,, (left + righty /2, ,
#4 eqn == Almial) / divide
i!
array ini
tO two halves’
//set, Ela
T= 13
JAE the etene,
nt is fo
rund
) ge (item < Almia])
ase tt ia - 4; /*
ane = ™ + /* compute n
ee tae ew right from th
Mm et 7S TE /* compute new teri ¢ @ right sub array */
a 2 ; ‘rom the
Jeewrn flagi left sub array */
1)
_spinary search technique ca
& rvalidity of the statement, mores
Ans :
Mesatement is not tue as it can Binary Searc
eer t would be less efficient than ara. h can be implemented using Linked List ~
ary search on an array so fast and efficient bee i i
sying array{middle]- le ofthe array just by
he same cannot be done with a linked list. One needs to write an algorithm to get the
The re nile node ofa Linked ist In a Knked is, one loses he aii to get he
value of any node in a constant time.
tne solation to the inefficiency of getting the middle of the linked list during a binary
wach fs to have the’ first node contain on addifons) pote that points to the nod:
te middle, Decide at the first node if one needs fo ‘check the first or the second half of
ihelinked list. Continue doing that with each half-list.
plemented using Linked list.” — Justify
(WBUT 2009]
[WBUT 2012, 2014]
6.Draw a minimum heap tree from the below list:
12,44, 7, 3, 10 5) OF 9,2
Now do the heap sort operation over the heap tree which you
the insertion sort algorithm.
Answer: Q
\ Part:
Thesteps are as shown below: @ ©
® ®
©
have formed. Write
psacii7
Scanned with CamScannerPerforming sorting in min heap will result in the array being sorted in descending ord
The array now looks like: ~5, 2, 0, 7, 10, 11, 3, 12,9 i
‘The steps for sorting are: ‘
Tree nodes: 9, 2, 0,7, 10, 11,3, 12 Sorted Array: -5
Tree nodes: 0, 2, 9,7, 10, 11,3, 12 Sorted Array: -5
Tree nodes: 12,2, 9,7, 10, 11,3 Sorted Array
Tree nodes: 3, 2,9, 7, 10, 1, 12 Sorted Array: 0, -5
Tree nodes: 2, 3,9, 7,10, 11,12 Sorted Array: 0, -5
~ Sorted Array: 3,2, 0, -5
Sorted Array: 7, 3,2, 0, -5
Tree nodes: 10,11, 12 Sorted Array: 9, 7, 32.0,-5
1,12. Sorted Array: 10, 9, 7, 3,2, 0, -5
12. Sorted Ariay: 11, 10, 9, 7, 3,2, 0, -5
Tree nodes:. Sorted Array: 12, 11, 10,9, 7,3,2,0,-5 +
2" Part:
so ist few objets are already sored, an unsoried object canbe inserted
in proper place. This is called insertion sort, it i te
at a time, inserting each in its suitable place foe ica ea
DSA=118
sorted).
m
them sequent
‘
7. Write the ps
Answer:
The Algorithm |
#include
0 and Afi] > key
DO Ali +1] — Ati]
isi-)
: Ali+ 1] — key
SORT. It tak
is sorted in S aS parameters an array A[l.. n] and the
Place: the numb
nu 7 ers are rearranged withi
bet outside the array at any ting, Sn
quence AI ..j—1j}
Wite the pseudo code for Heap sort. de wearin
Answer
The Algorithm for heap-sort is as follows.
clude
{include
fiefine N 6
wid buildheap(int{], int);
wid heapsort (int[{], int);
int main(void)
{
int heapArr[N] ={15, 19, 10, 7, 17, 6);
int i;
print£("\nBefore Sorting: \n"):
for (i = 0; i < Nz it+)
printf ("$d\t", heapaArr (il);
buildheap(heaparr, N);
heapsort (heapArr, N)7
print€(*\nafter Sorting: \n")7
for(i = 0; i < Ny itt)
printg(*ga\t", heapAry[il);
Beteh() ;
jfeturn 0;
ia bu
{'@ buildheap(int xf], int n)
. psAa-119
Scanned with CamScannerEE
POPULAR PUBLICATION
fe(s-0/ y < val)
2:
nilé (3 >-0 && xlf
© ts) = xIfl
ae
fi A
(ae - 2) 02%
sajna
)
int n)
doia heapsort (int x1), in!
: s.
int i, Ss,
for (i=n- i
value;
ees so de)
ivalue = x(ily
x(i] = x{0)s
sal;
if (i > 2 a& x[2] > x[1])
s = 2;
while (s >= 0 && ivalue < x[s]) 1
{
x
£
s
(£] = xs):
oc
s2.4f4a;
- 1 && x{s] < x[s + 1))
if (s>i-0)
ze -h
x{£] = ivalue;
a :
i :
8. Deduce the average time complexity of Quicksort algorithm.
Answer:
The basic idea of Quicksort is as given below:
|. Pick one elemént in the array,
2. Make one pass through the a
so that:
* the pivotis in its Proper pl:
P lace,
* entries smaller th; be
* entries larger than the pivot are to its right.
DSA-120
which will be the pivor. nse
ray, called a partition step, re-arranging
lan the Pivot are to the left of the pivot.
Recu
Z and t
sis
ae T+
eins
the time 10
°
°
pe average ¥
TNS TO) i"
TN) =2N
Multiply by N
NT(N) = 208
To remove th
(N-DTON-1)=
and subtract:
NT(N) - (N-L
Prepare for tel
NT(N) = (N+
Divide by NN
TIN)(N+1) =
Telescope:
TIN)(N+1)
T(N=I)AN) =?
T(N-2)(N-1) -
» TRY3 = Ty
Add the equati
TN)N+1) =
TN) = (+1,
The sum (1 ji
Thus TN) = ¢
8. What 1
dane is the
Answer;
Scanned with CamScanner7 SUCTURE & ALGORITHM
recursively apply quicks
: ‘ ort to th
and to the right part of the \e part of th
¢ array. array that is to the left 0 .
ft of the pivot,
alysis . i
ya Td) + TUN = i-1) +N
ine 0 0 he fei equal to
the time to sor
rt the left partition with iclements, ph
, plus
othe time to sort .
i the right partition wi
othe time to build the mre With Neil elements, plus
average value of T() is IN ti zs
TNsT@).j = OthruN-1 times the sum’ of T(0) through T(N-1)
10) =2N (STG) + eN
oltiply by N
NTN) = ra +cN*N
Toremove the summation, we rewrite the equati :
uyTiN-1) = 28 TG FANT -quation for N-1:
A = 2T(N-1) + 2cN -c
tel a ‘ .
Tino ea terms, drop the insignificant c:
Divide by NONI):
TINYINEL) = T(N- LN + 2c/(N+1)
Telescope:
TNY(N+1) = TIN-1)/N + 2c/(N41)
TINIAN) = TON-2/(N-L}+ 20/(N)
TIN-2V(N-1) = T(N-3)/(N-2) + 2e/(N=1) ‘
TyB=T(1y2 + 2/3
“i the equations and cross equal terms:
Tnyotel)= TUL). #26 8 (MH). 31° NH
IN) =(N+1\(1/2 + 2c SCA)”
vo § (Ii), j =3 to N-I, is about LogN
T(N) = O(NlogN)
i i } .
ae is the primary criterion of performing bina
ry search technique on a list of
[WBUT 2015]
Ans
‘ei ientl ing a sorted list to
IY se ii method of efficiently processing a sortel 1 e
eerie sr ealte of the sorted criteria. It does so by “cutting the
‘h iteration comparing the
‘ermine ro i
ws that match a given dly, with eacl
ied value is greater
i repeates
bins) tas ‘made. If the SUPP"
a in half (thus the term pe
Value with the value where the Co ft ue is greater
f 1 is ignored, thus. eliminating
a a tec " data te skipped value is less than
ed
: The reverse hap!
0
Compare those values.
psA-12!
Scanned with CamScannertil there are no
ison repeats Un More
comparison Vag
inate the need to do a comparison
conquer S
jteria. This
ch criteria. T!
= Jombine the
the supplied st
ire. a ble to elimi * .
Tag chat eons nae anna |=
in doing s f sorte Fe abj;
the records, and in ‘ag the smaller set of S eto a
,eding to load all mere
our search criteria. Heer C int x
tor? why do we need hashing? How does @ hash tabs if (1c
10. What is Load ria Many umber chosen for computing a hash function» t
(1) searching? Why is P : ety |
ay
Answi
1" Part: . " of records to the numb,
Lands fector refers to the ratio ofthe number er OF addr }
retur
within a data structure.
! Part: oo a
Hashing is used to inbox and retrieve items in a database because it is faster to fing
item using the shorter hashed key than to find it using the original value,
3" Part: 7
J hash table is an array containing all of the keys to search on. The position of cachje |
s determined by the hash function, while can be any function which aay
in the array i
maps the same input to the same output. So, we shall assume the hash function as 0({),
)
7+ Merge fui
nerge(int a
{
int i,
i=low;
k=low;
4" Part: .. while |
The prime numbers are used to minimize collisions when the data exhibits oa
particular pattem, The reason prime numbers are used to neutralize the effect of paten,
in the keys in the distribution of collisions of a hash function.
1. a) Explain with an example the Merge sort algorithm.
b) Write an algorithm for Merge sort. on [weUT:
OR, “J
Show the operation of merge sort with an exam
ple. (weuT2
©) Compare the best case time complexity of selection sort and insertion sort
Answer: a
2) Merge-sort is based on the divide-and-conquer paradigm. The Merge-sor aet®|
can be described in Pat
1 Divide Step general terms as consisting of the following three steps:
DSA-122
Scanned with CamScanner/gesore (int all, int 1,
int_ mid;
j£(lowshigh)
(
i
return (0);
| yerge function*/
i fi
int i,
islow:
jemid+1;
kelow:
{
while(ic=mid)
specursive Merge’ Sort
algorithms,
ow, int high)
mid=(1ow+high) /2;
mergesort (a, low,mid) ;
mergesort (a,mid+1, high) ;
merge(a,low,high, mid) ;
+k, €[50];
while ( (i<=mid) && (j<=higl
if(ali)
3 .
Let the original unsorted array is: 8 4525
Inthe fist step it gets split into
8 4) 525 (ll denotes the divider) '
Parter splitting and merging is shown in the next steps: :
8 | 4 I 52.5 (split)
8 ie ls 25 Gm split, merges a single-element array on returns)
8 [4 ff 82 3 (cant spit, merges a single-element aray an returns)
48 |] 52 5 (merges the two segments into the array)
48 I] 5 I] 25 (split) 7 ;
448 [5 | 25 (cant split, merges a single-element array and returns)
48] 5 I 2 [I S(split) :
48 | 5 [2 I] 5 (can't split, merges a single-element array and returns)
lit, merges a single-element array and returns)
48 I] 5 || 2 I] 5 (can't sp) "
48] 5 [2.5 (merges the two segments into the array)
48 ||| 2 5 5 (merges the two segments into the array)
2.455 8 (merges the two segments into the array)
©) Selection sort Performance: Best Case is O(n*) because even if the list is |
same number of selections must still be performed. :
Insertion Sort Performance: The best-case time complexity is when the aray ial
sorted, and is O(n). ;
|
.2. a) Explain with a suitable example, the principle of operation of Quick sor.
A _ [WBUT 2007, 200,
In Quick-Sort We divide the array i i
i T y into two halves. We select a pivot element (
ihe’ mide clement of the array) & perform a sorting in such a manner thal
lemen ee the left of the pivot element is lesser than it & all the elements toi
rater than the pivot element. Thus we get two sub arrays. Then we recursively
ou function on these two sub arrays to perform the necessary sorting.
{us consider the following unsorted array: e
a[] = 45 26 77 14 68 61-97 39 99 90.
Step I:
We ch indi ‘ be
ae < aaa ee ta ay = 0 and right = 9, We find the pivot element bythe
]/2= a [4]. So the pivot element is a.[4] = Mi
with a [left] =a (0]= 45 and a fright) = a [9] = 90
DSA-124
Scanned with CamScanner
step
Wwe comp:
right by |
element. \
right=7.
step 4:
since left.
The array
step 5:
We further
ice., left
We repeat
We will se
will find tt
pivot elem
of quick so
b) Find the
Answer:
Refer to
3. a) Why i
Proven t
‘ypically us
given const
Placed into ;BATA STRI E & ALGORITHM
2
if
57 ynpare all the elements to the left ofthe pi
‘each time, When an element is less than
y the latest 68.
Resear he lates value of left. In our exams Wo St0P When there is ho such element,
imple the left vatue is 2 ie., left=2.
ety !
ag It is
et. We record the latest value greater than 68. We stop when there is no such
rahe
S004 <= right we swap b
gine left <= etween a [I " :
Sereray now Tooks like a [left] and a [right]. That is between77 and 39.
45 26 39 14 68 61 97 77 99 90,
S05 er increment the val
‘We further i ent the value of left and di i 7
ee ed and ight =7-1" 6 lecrement the value of right by | respectively
erepeat the above steps until left <= right.
We will see that at one stage that the left and right indi i
: te ight indices will cross each other and
wil find that our array has been subdivided. That all the elements lying to the eft of the
fivot element is less than it and all to it's right are greater. We then make recursive calls
afqick sort on this two sub arrays. :
t)Find the complexity of Quick sort algorithm. [WBUT 2007, 2013]
Answers,
Iefer to Question No. 8 of Short Answer Type Questions. ah
[WBUT 2008]
.2)Why is hashing referred as @ heuristic search method?
Answ :
Abeuristic algorithm, is an algorithm that is able to produce an acceptable solution to a
toblem in many practical scenarios, in the fashion of a general heuristic, but for which»
fee is no formal proof of its correctness. Alternatively, “t may be correct, but may not
te proven to produce an optimal ‘reasonable resources. Heuristics are
‘pealy used when there is no known-method to find a optimal solution, under the
Ben constraints (of time, space etc.) or at all. It is a technique whereby or items are
Peed nto a structure based on a key to-adéress transformation.
use Hashing for
Peforming optimal searche
qtereases speed, betters €
fata and reduces overhead. ah h
3s why hashing are sometimes referred #5 peuristic sear
¢ of hashing ov
solution, oF to us
OC!)
ta at a constant time :
searching of
retrieval of dat ; .
af proves retrieval, optimizes
fase of transfer, im
‘method.
ic search algorithms?
er deterministic 603 ot oa)
y
Nhat isthe primary advantag'
psA-125
Scanned with CamScannerPOPULAR PUBLICATIONS
Answer: . 11 the data items sequentiay
In detérministic search method we try 10 €XPIOTE ®t hashing is th MY: Oy
‘one which gives different polynomial Ce 7 (1). Is this sense hice 5 -
method where the searching time is 28 “AlWaye
lision
eco
Tision taks
co callision
imeour exam
19 Ove acy lis
advantageous. : 2
¢) Define collision, Discuss two collision resolution techniques and Compare, adi
performances. v3
oR, = t
Discuss different collision resolution techniques. DWBUT 2015, a
Answer: '
Answer between two Keys K & K’ occurs when both have to be stored in the aye |
both hash to the same address in the table. a
sion resolution techniques ar : i
pe i dvosings It collision resolution scheme for a hash table, nq. fA hash table,
© Open addressing: It is a general |
Streolision, other positions of the hash table are checked (a probe sequence) uni
empty position is found. * is
The different types of Open addressing scheme include:
a) Linear Probing (Sequential Probing)
b) Quadratic Probing
) Double Hashing (Re Hashing)
# Chaining: It is a collision resolution scheme to avoid collisions in a hash table |
making use of an external data structure. A linked list is often used. ‘a
a
jateger value
complexity te
achieve the av
function is not
‘And hence all
Therefore, t0 |
element in a li
d) Why the ha
Answer:
Linear Probing: : The reason is t
Refer to Question No. 2 of Short Answer Type Questions. con
. at do yo
Chaining: In open addressing, collisions are resolved by looking for an open celine | path tables t
hash table. A different approach is to create a linked list at each index in the hash tbleA | Anges”
data item’s key is hashed to the index in the usual way, and the item i3 inserted it Hashing is a
: m
gtlete and sear
Se Operati
- ion:
picall °
is peally looks
Hoke ist that index. Other items that hashes to the same index ae simply adel wi
inked list at that index. There is no need to search fe i imary ta
table array. This isthe chaining methods nT PLY cells in the wt
Let us consider the following elements
89, 18, 49, 58, 9, 7, tn record
(Using Division ~ Remainder Method) However
(Using Division ~ Remainder Method) tical to in
(Using Division = Remainder Method) cals involves
H(S8) =2 (Using Division - Remainder Method)
aul 2 (sing Division - Remainder Method)
Y there is one element in the position 2, which is 5
9 is also hashed to position 2, which } When
is al Which i ii DI
situation occurs we say that a collision eae 1 ‘oe
DSA-126
Scanned with CamScannerjsion avoided by ch
place \ ad 9 adjacency list re
Hey Hist to the eo ee semIation. Whenever a
responding header where
inple collision occurred at
any further collision
head 2 Sow
‘ader node 2, g
\ 10 We ju
CUTS aL 2 We add it to our
oh
add 9 and $8 to it as an
existing li
sgnable uses hash Tunetions to compute
npute an integer value for searchi i
aiye can then be used as an index into an array, gi ing te ea seat ue
, stant time
sity to find the requested data, How ‘i i
qe average Lime complexity of O (1). Inthe hase ble keer ence Nees
ive th ).. If the hash table is very small or the hash
evs not good enough then the elements ear star to buildin one index inthe aay,
“Pennce all n elements could end up in the same linked list associated to ‘hat index
ve, to do a search in such a data arrangement is equivalent to looking up a data
atin linked list, something, we already know to be 0 (n) time:
it
[WBUT 2008]
ity the hash functions need to be simple?
we
reason is that, the computation itself will consume less amount of time.
1g? What are the applications where you will prefer
tures? What do you mean by collision? How is it
[WBUT 2011}
iis a method for storing and retrieving records from a database i les you se,
end search for records based on a search Key value. When proper 1 ronan
eons can be performed in constant time, Infact, @ POPS os This
Fy loks at only one or two records for each search. or dete option, Ts
ter than the O(log») average cost required to 2 a e ‘ ny
"Sords, or the O(log m) average cost required to do 7 oH
vere, even though hashing is based on & "0 o su
ri implement properly. Designers need 10 pay
sehched with implementing a hash SIs
28m stores records in an arvay €2¥
ie 2 computation on @ search Key Kit
in AT that contains the record with ey Fi Te
bash function, and is usually denoted’?
ie in the table in whatever order SM
‘ordered by value. A posit
7 HT). Hashing works by
= tae intended to identify the
i joes this calculation
ashing schemes
1 calculation,
: known as @ slot. The
Scanned with CamScannerPOPULAR PUBLICATION .
il sjoted by the variable M with
table HT will be de slots vate an algori
pf technique.
30!
number of slots in hash
from 0 toM- I. : :
The goal for a hashing s)3te% is to orange :
some hash function hy i= ie nie
key ofthe econ stored at HT equal 10 Be many wes finer “a
Hash tables are c ; St eel men eg
i fe arrays (array’ : Pest
used to, implemen ea ray terpreted programming, languages like AWE
cor BP. Ted ep ables ean be used to implersens caches, auxiliary data tabies gu
and PHP.
ie arly stored in slower media, tn this ®
‘ess to data that is primar fia, inthis
fa resins ‘an be handled by discarding O° a cs avo colliding entice
Casing the old item that is currently stored in the table and overwriting it with
item i que hash value. ‘ A
Soy item in the table has a uni wie
item Tejon between two Keys K & K’ occurs when both have te tte in ay
i le.
h to the same address in the tab! 7
cael probing ae i Tor resolving, hash collisions of values of hash fig
sequentially se able for a free location. This is accompli
Jhing the hash table
-quentially searching
things such that, for any ke :
table such that 0 <=i:< IM, se 2
emi
Theme each ASS
Data then third a
sorted.
wegenotes th
q@ selecsort
oi
vorat loc. min
sme as a starting value and one as 2
aia arithmetic. The second value, which is the same for all keys and knoy if (all
stepsize, is repeatedly added to the starting value until a free space is found, o thes {
table is traversed. ; min =
The function for the rehashing is the following: loc =
rehash(key)=(a+1) % k3 | 5 )
For example, we have a hash table that could accommodate 9 information, and he if (lec !
te stored were integers. To input 27, we use hash(key)= 27 % 9=0. Therefae C
stored at 0. If another input 18 occurs, and we know that 18 % 9= 0, then a cali temp = a
‘ould occur, In this event, the need to rehash is needed. Using linear probing. 1 alil =a
a alloc] =
r. Since | is empty, 18 can be stored init. | '
the rehash(key)= (18+1) % 9
es it differ from
[WBUT 2008, aon print ("\nth
for (i = 0;
Printe("$3
5, a) What do you mean by external sorting? How do
sorting?
Answer:
External sorting is the method when the sorting takes place with the seconde Mt
The time required for read and write operations are considered to be S|
sorting with disks, sorting with tapes.- . s
lteral sorting on the ther hand is defined as sorting mechanism where
takes place within the main memory. The time required for read and write
Time
omplexit
For first paes the
considered to be insignificant e.g. Bubble Sort, Selection sort, Insertion sort? eG
ere sate is faster than external sorting because in external somins mye
funsider the external disk rotation speed, te latency time et. Such ope. ey
i an array or a linked list ora hash table. Consumection so
( um
OB the amin
DSA-128
Scanned with CamScanneraSconding order using solection
(WBUT 2008, 2018]
a
wet nique. 9 2 list numbers in
on then third and so on. We ' are placed in the first position, then
ca ‘Ocess until all the elements of the array
ses noces the no. of elements
Ln selecsort(int al), int n) (
wr, loc, min, temp, i, 3;
me = 0; 2 * &39: 562, 674
b) Find the time compton ™
DSA-132
Plexity of Binary Search Algorithm.
30,20
30 20
20,30
2M Par
Suppos'
generali
We can
list in th
bu
= s7(2) +3on :
What to
x
where a,
ra
{
bu
bu
bu
}
More.
Tac
Wh;
C
Scanned with CamScannerITH!
INPUT 1" pass >n0
199 ag 2h3 3 PaSs Gorted)
205208 ae
ORE 6 S62 cage 189
at 674 939 192
097 205-569 205
192 535 674 - 421
535 986g 535
839° O97 gg: we
Bee ie ge oad
674 939-997 ue
part: 5
ees we have a list of n records each with a key that's a number from | to k (we
Jize the problem a little so k is not necessarily equal to n).-
ecan solve this by making an array of linked lists. We move each input record into the
jainthe appropriate position of the array then concatenate all the lists together in order.
pucket sort (L) i
(
list Y[k+1] : :
for (i = 0; i <= ky i++) YEA) = empty
vhile L nonempty
let X = first record in L
move X to Y[{key(X)]
! ;
for (i = 0; i <= "ky i++)
concatenate Y{i] onto end of ©
‘i sntatior
ato do when k is large? Think about the decimal represel
ooo d+-
x=a+10 b+ 100 c + 1000
are e
vee abjc etc all in range 0:.9. These digits
tadix sort (L
(
yn of anumber
do bucket sort.
asily sitall enough t0
bucket sort by @
bucket. sort by b
bucket sort by ¢
}
“simply
POX sort (L) :
‘Pie (some key is none
5 mod 10)
psa-133
ro)
bucket sort (keY*
Scanned with CamScannerPOPULAR PUBLICATIONS
keys = keys / 10
) vith th 2
ing i ne with the most effeg
: sorting is the 0 me a
i ing, ass of bucket sort! ons aportant digits, The et a
In radix sorting, the ie be the one usin the m ee rAiek tae i oe ie
overall oder. So we want 10 bE Care of th oe
bucket sorting passes are
same key (mod 10) on the last pass-
is as follows: 4
Jexity is thus O(logen) ini
sary Search
split into two hal
The time comp!
b) The time complexity of Bim
In each iteration, the array is
search takes the form of a binary tree.
also.
OTS cay
re appropriate than Binary search? yy,
Pe Write an algorithm for interpolation sean! |
M wontnat worst case time complexity of interpolate
case time complexity of interpolation searghy
9, When will interpolation search be mer
does an ‘interpolation searc
Show with an appropriate examp!
search is O(1). What is the averag
BUT 259
interpolation search works better than Binary Search for a sorted and unifomy ) a
distributed array : | opie
Interpolation search is an algorithm for searching for a xiven Key value in an inde |
array that has been ordered by the values of the key. It parallels how humans sea |
through a telephone book for a particular name, the key value by which the book's ens |
are ordered: In each search step it calculates where in the remaining search space tie —
sought item might be, based on the key values at the bounds of the search space andite
value of the sought key, usually via'a linear interpolation. The key value actually founda
this estimated position is then compared to the key value being: sought. If jt is not eq
then depending on the comparison, the remaining search space is reduced to the pat
before or alter the estimated position. This method will only work if calculations on
size of differences between key values are sensible.
without disrur
Why?
Answer:
a) Sorting is a
based ona dat
decreasing fash
b) Stable sort:
When sorting s
sort order. The
Part of the datz
whenever there
original list, th
en equal el¢
“ala Where the
pte iF all keys
Algorithm: INTERPOLATON SEARCH
/* Given: x, and a <...< ay,
such thatx =a,
O if no such i exists */
i=l
n
fia, APlace Sortin
Hi ces
ifxHI then i vn th
Joop invariant: x>LO and x
1.
#3AG yde
tructure for a node +,
int data;
struct Node *next
yunction to insert a’ no .
é ree reAtTheBegin (etruce fe
function to bubble sort t Node **start_ret, int
§ pubbleSort (struct Node econ + int data) ;
fynction to swap data of -_
is (aeruct ode] fa feccace meas brs 1
function to print nodes in a eison th
printList (struct Node datare\ sat linked list */
function, int main)
BUT 2015, 2017]
‘unction maps
svenly, distributed,
jnt arr{] = (12, 56, 2, 11,
int list_size, ii
y+ start with empty linked list */
struct Node *start = NULL:
/* create linked list fro
created linked list, wil
for (i = 0; ix 6; i*4)
insertAtThel
/* print lis!
printé(*\n Lis
printList (start)?
+ before sort:
inked list bel
pegin(astart, axe (il):
/* sort the Linked list 7
pubblesort (start) +
m the array arr()-
be 1->i1->2-256->22 */
do
eS Not compose the array
(weur 2016)
he é
begining of a Linked lsit */
ven Linked Ysit */
+ 903;
ing */
fore sorting ")?
/* print list after sorting | loeting "3
printf ("\n Linked list af’ :
printList (start) ;
getchar (Vi - : oa
return 0; te cae g waked HE
My node at the veil, int date)
‘uncti engert 2 20 weg
rerien esac |
ex
psa-137 :
i
Scanned with CamScannerPOPULAR PUBLICATIONS
aptri = (struct Node
struct Node
data:
ptri->data a
ptri-snext = *staxt_refi
*start_ref = ptrli
} x
7+ punction to pri
yoid printList (struct Ni
nt nodes in a given
jode *start)
f 5
aeruct Node *temp = starts
printé("\n");
while (temp
ILL) 2
printé("#d *, temp->data);
temp = temp->next;
}
2 . ;
/* bubble sort the given linked lsit */
void bubbleSort (struct Node *start)
(
int swapped, i;
struct Node *ptr1;
struct Node ‘lptr = NULL;
/* Checking for empty list */
if (ptrl == NULL)
veturn;
do
(
swapped = 0;
ptrl = start;
stl (pt¥l->next != Iptr)
if (ptrl->data > ptr1->next->data)
Swap(ptr1, ptri-> .
swapped = 1; mere):
) Pel = ptrt-onext;
) es pert;
) while (swappeq) ;
/* function to
: swap -¢
Void swapistruct nejent? Of two nodes a and bé/
+ struct Node *b
*b)
DSA-138 a
+)malloc (sizeof (sexy,
ice
linked list *;
Scanned with CamScanner
b) Linear sei
Obviously. t
array. In this
Likewise, th
equal-to the
made.
14, Find the
assuming t
Answer:
Refer to Qu
15. Write st
a) Radix so
) Merge S
©) Interpota
-4) Heap
Answer:
a) Radix soy
adix sortin
Successive
oreying the
ihe digit |
Tyre.
e .,
Ste ollowir
‘Ps invoty,
S| the ojnt temp = a-saal
ta;
wiodata = b->data,
temp;
_) Write an algorithm for
. give an outline of the for linear search,
omplexity
Y of :
Your algorithm, QD
a)
) search (Ar:
jnear : ray A,
gant: set i to 1 -
if i> n then
3. if Ali) = x then 7 step 7
Lue x)
steP ‘|
Sep dz Set i to ish O'step 6
fep 5 GO £0 Step 2
; Print Elem
steP ent x Found at i
+ pri at, inde:
Sep 7: Print element not £ x i and go
see? Oy exit ound, go to step 8
1p Linear search exeeutes in O(n) tine where ni ‘
Oh In this case, only one comparison will be made eee
tnewise, the worst case will happen when either VAL is not present i 5
is not it itis
equal-to the Jast element of the array. In both'the cases, n amoral aie Be
made.
{4.Find the time complexity of merge sort technique using the recurrence relation
assuming the size of the list n=2'. s [WBUT 2017]
Answer: - :
Refer to Question No. 7 of Long Answer Type Questions.
a short notes on the following: wou 200 aa
t) Merge Sort AyBUT 2014)
dinerpotation ‘search [WBUT 2015, 2018]
leap
Answer: é
4)Radix sort: 2 sae tg values. THe values
Radix sorting i «ue for ordering a list of PON je ig accomplished by
sorting is a technique i left. This we tythe ‘position
sucess git positions. from, 7 ket is given DY
ively ordered on pe Syere he index for thes = sername te Ht must be
{ying the values into "bUCKEtS.’ WT ocitions have
“ie digit being sorted. Once @l digit positions : et during te four
Sted, ves th Og 78 9. Dung
equernces 5.30) Tui are ere
ae
ollowing table shows the 5 987
ivolved in sorting the list 24 852 batt pass 2 te fens pla
RSs the ones place digits a"° ° ed, DU
-psa-339
Scanned with CamScannerCE
popys =< PUBLICATIONS
y the earlier pass. ON pass 3 the
fon tb: fl ; i
ani the eave poston of values ave ordering: Ae NN _
save digi are ordered, again retaining the pt ree cou re
place digits , = as
the result is an ordered list. ant ie
bucket, Br Fron | {0 78 : os
o pon I}
1 {30lt| — opr a8 ee ‘ve
3 7[3]0 a
7 St] (415426 i
a
#include Lea os
#define N 11 “
#define SHOWPASS _
; int£(
void radixsort(int[], int); printt
void print(int[{], int); eta
init main (void) :
/* Output
int unsortédArr[N] =(624, 852, 426, 987, 269, 146, 415, 301, :
730,
int i;
printf("\nBefore Sorting: \n\n");
for (i = 0; i < N; i++)
printf("$5d", unsortedArr[i]);
radixsort (unsortedArr, N);
printf("\n\naAfter Sortin
78, 593};
in");
for (i = 0; i < N; iss)
Printf("$5a", unsortedarr{i});
getch();
return 0;
} Qi
void radixsort
{
int i, DIN], m=
int count = 0;
for (i = 9
{
Pi my
m = ali);
while (m / exp > 0)
DSA-140
Before Sortir
624 852 4
PASS 1:
730 301 8
PASS 2 ;
301 415 6.
Pass 3
78 146 26
Mier Sortin,
78 146 26
u
Scanned with CamScannersot i eket (101 =(0);
y= OF icn;, i
x oket ali] / exp ¥ 19
pee ate i < 10; wa
cket (il += buck
mucter nt ty dpe Spee
for Cpucket (ali) iiexp.
(= 07 d