17484 answe key gate 2014 instrumentation engineering

Upload: anonymous-8pcxxs

Post on 03-Jun-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    1/52

    EC2202 -DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++

    L T P C 3 0 0 3

    UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 9

    Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects,constructors and destructors ,operators overloading and type conversions

    UNIT II ADVANCED OBJECT ORIENTED PROGRAMMING 9

    In!eritance, Extending classes, "ointers, #irtual $unctions and poly%orp!is%, File &andlingTe%plates ,Exception !andling, 'anipulating strings

    UNIT III DATA STRUCTURES & ALGORITHMS 9

    (lgorit!%, (nalysis, )ists, Stacks and *ueues, "riority *ueues-inary &eap-(pplication, &eaps!as!ing-!as! tables it!out linked lists

    UNIT IV NONLINEAR DATA STRUCTURES 9

    Trees-inary trees, searc! tree (T, (#) trees, .rap! (lgorit!%s-Topological sort, s!ortest pat!algorit!% netork $lo proble%s-%ini%u% spanning tree - Introduction to /" - co%pleteness

    UNIT V SORTING AND SEARCHING 9

    Sorting Insertion sort, S!ell sort, &eap sort, 'erge sort, 0uick sort, Indirect sorting, ucket sort,Introduction to (lgorit!% esign Tec!ni*ues .reedy algorit!% 1'ini%u% Spanning Tree2, ivide andCon*uer 1'erge Sort2, yna%ic "rogra%%ing 1(ll pairs S!ortest "at! "roble%2

    TOTAL HOURS = 4

    TE!T BOO"S#

    3 'ark (llen 4eiss, 5ata Structures and (lgorit!% (nalysis in C6, 7rd ed, "earson Education(sia, 899:8 E alagurusa%y, 5 ;bject ;riented "rogra%%ing it! C++6, 'c.ra &ill Co%pany )td, 899:

    REFERENCES#

    3 'ic!ael T .oodric!, 5ata Structures and (lgorit!% (nalysis in C++6, 4iley student edition, 899:8 Sa!ni, 5ata Structures ?ean "aul Tre%blay @ "aul .Sorenson, (n Introduction to data structures it! applications, Tata'c.ra &ill edition, II Edition, 8998A ?o!n B&ubbard, Sc!au%s outline o$ t!eory and proble% o$ data structure it! C++, 'c.ra-&ill,/e el!i, 8999= jarne Stroustrup, T!e C++ "rogra%%ing )anguage, (ddison 4esley, 8999: Bobert )a$ore, ;bject oriented progra%%ing in C++, .algotia "ublication

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    2/52

    UNIT I

    PART A

    $% '() * (, *.,)*/*.1

    Identi$iers are na%es $or various progra%%ing ele%ents in c++ progra% suc! as variables, arrays,$unction, structures, union, labels ect, (n identi$ier can be Co%posed only o$ uppercase, loer caseletter, underscore and digits, but s!ould start only it! an alp!abet or an underscore2% '() * ( .51

    Deyords are ord !ose %eanings !ave been already de$ined in t!e c co%piler T!ey are also calledas reserved ords1ex2 %ain12, i$, else, else, i$, scan$, print$, sitc!, $or, goto, !ile ect,3% D./*,. 65,)(,) *, 6++%

    Constants in c++ re$ers to $ixed values t!at do not c!ange during execution o$ a progra%4% D./*,. ( 7(*(8.%

    ( *uantity ,4!ic! %ay vary during execution o$ a progra% is called as a variable% '() (. :,( 5;.()51

    T!e operators t!at act upon a single operand are called as unary operators T!e unary operators used inc++ are - , ++, -- and sieo$ operators% '() * ?.(,) 8 (, .@;.*5,1

    (n expression is a co%bination o$ constant, variable, operators and $unction calls ritten in any $or% asper t!e syntax o$ t!e c++ language9% S)(). )'. *//..,6. 8.).., 6 (, 6++%

    C C++1i2 "rocedural progra%%ing language ;bject-oriented progra%%ing anguage1ii2 .lobal variable can be declared It is an error to declare a variable as global1iii2 Function prototypes are optional (ll $unctions %ust be prototyped1iv2 )ocal variables can be declared only )ocal variables can be declared any !eret!e start o$ a c progra% in a c++ progra%1v2 4e can call a %ain12 $unction, it!in T!is is not alloeda progra%$0% L*) )'. 7(*5: 55; 65,6.;)

    Four %ain ;;" concepts(bstractioncreation o$ ell-de$ined inter$ace $or an object, separate $ro% its i%ple%entationeg, key $unctionalities 1init, add, delete, count, print2 !ic! can be called independently o$ knoing!o an object is i%ple%entedEncapsulationkeeping i%ple%entation details 5private6 ie, inside t!e i%ple%entation !ierarc!y an object is de$ined inter%s o$ ot!er objects Co%position L larger objects out o$ s%aller ones

    In!eritance L properties o$ s%aller objects are 5in!erited6 by largerobjects"oly%orp!is%use code 5transparently6 $or all types o$ sa%e class o$ objectie, 5%orp!6 one object into anot!er object it!in sa%e !ierarc!y$$% D./*,. 6( (, 58.6)

    ClassK It is de$ined as blueprint or it is a collection o$ objects;bjectsK is an instance o$ a class

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    3/52

    (l%ost like struct, t!e de$ault privacy speci$ication is private !ereas it! struct, t!e de$ault privacyspeci$ication is publicExa%pleKclass pointMdouble x, yN GG i%plicitly privatepublicKvoid print12Nvoid set1 double u, double v 2NON$2% D./*,. *,'.*)(,6.

    In!eritanceP ;bjects are o$ten de$ined in ter%s o$ !ierarc!ical classes it! a base class and one or %ore levels o$classes t!at in!erit $ro% t!e classes t!at are above it in t!e !ierarc!yP For instance, grap!ics objects %ig!t be de$ined as $ollosKSyntax $or In!eritanceclass derivedClass K public baseClass Mprivate KGG eclarations o$ additional %e%bers, i$ neededpublicKGG eclarations o$ additional %e%bers, i$ neededprotectedKGG eclarations o$ additional %e%bers, i$ neededO$3% D./*,. .,6(;:()*5,

    Encapsulation is one o$ t!r %ost i%portant $eatures o$ a classIt is t!e process os co%bining %e%ber$unctions and t!e data it %anipulates by logically binding t!e data ane keeping t!e% sa$e $ro% outsideinter$erence$4% D./*,. (8)(6)*5,%

    Creation o$ ell-de$ined inter$ace $or an object, separate $ro% its i%ple%entationeg, key $unctionalities 1init, add, delete, count, print2 !ic! can be called independently o$ knoing!o an object is i%ple%ented$% D./*,. ;5?5;'*?

    "oly%orp!is% %eans 5!aving %any $or%s6 It allos di$$erent objects to respond to t!e sa%e %essagein di$$erent ays, t!e response speci$ic to t!e type o$ t!e objectEg t!e %essage displayetails12 o$ t!e "erson class s!ould give di$$erent results !en send to a Studentobject 1eg t!e enrol%ent nu%ber2$% D./*,. ()( '**,%

    T!e purpose o$ t!e exception !andling %ec!anis% is to provide a %eans to detect and report an

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    4/52

    5exceptional circu%stance6 so t!at appropriate action can be taken$9% '() * )'. :. 5/ 65;. .5:)*5, 5;.()51

    In C, t!e global version o$ t!e variable cannot be accessed $ro% it!in t!e inner block C++ resolves t!isproble% by introducing a ne operator KK called t!e scope resolution operator It is used to uncover a!idden variableSyntaxKKK variable na%e20% '., * 5: ?(. ( /:,6)*5, *,*,.1

    4!en t!e $unction de$inition is s%all, e can %ake t!at $unction an inline $unction and e can %ainlygo $or inline $unction to eli%inate t!e cost o$ calls to s%all $unctions2$% '() * 57.5(*,1

    ;verloading re$ers to t!e use o$ t!e sa%e t!ing $or di$$erent purposesT!ere are 8 types o$ overloadingKP Function overloadingP ;perator overloading22% '() * )'. *//..,6. 8.).., ,5?( /:,6)*5, (, ( .6:*7. /:,6)*5,1

    ( recursive $unction is a $unction, !ic! call it !ereas a nor%al $unction does notBecursive $unction cant be directly invoked by %ain $unction23% '() (. 58.6)1 H5 (. )'. 6.().1

    ;bjects are basic run-ti%e entities in an object-oriented progra%%ing syste% T!e class variables areknon as objects ;bjects are created by using t!e syntaxKclassna%e obj3,obj8,,objnN1or2 during de$inition o$ t!e classKclass classna%eM-------Oobj3,obj8,,objnN24% L*) 5?. 5/ )'. ;.6*( ;5;.)*. 5/ 65,):6)5 /:,6)*5,%

    P T!ey s!ould be declared in t!e public sectionP T!ey are invoked auto%atically !en t!e objects are createdP T!ey do not !ave return types, not even void and cannot return valuesP Constructors cannot be virtual)ike ot!er C++ $unctions, t!ey can !ave de$ault argu%ents2% D.6*8. )'. *?;5)(,6. 5/ .):6)5%

    ( destructor destroys t!e objects t!at !ave been created by a constructor upon exit $ro% t!e progra% orblock to release %e%ory space $or $uture use It is a %e%ber $unction !ose na%e is t!e sa%e as t!eclass na%e but is preceded by a tildeSyntaxKclassna%e12M O2% D./*,. ,(?*6 8*,*,%

    yna%ic binding %eans t!at t!e code associated it! a given procedure call is not knon until t!e ti%eo$ t!e call at run-ti%e

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    5/52

    PART B

    PART B

    $%E@;(*, )'. 8(*6 65,6.;) 5/ 58.6) 5*.,). ;5(??*, *, .)(* *)' .@(?;.%

    O8.6)# ;bject is t!e basic unit o$ object-oriented progra%%ing ;bjects are identi$ied by its uni*uena%e (n object represents a particular instance o$ a class T!ere can be %ore t!an one instance o$ aclass Eac! instance o$ a class can !old its on relevant data

    (n ;bject is a collection o$ data %e%bers and associated %e%ber $unctions also knon as %et!odsC(.# Classes are data types based on !ic! objects are created ;bjects it! si%ilar properties and%et!ods are grouped toget!er to $or% a Class T!us a Class represents a set o$ individual objectsC!aracteristics o$ an object are represented in a class as "roperties T!e actions t!at can be per$or%ed byobjects beco%e $unctions o$ t!e class and are re$erred to as 'et!ods For exa%ple consider e !ave aClass o$ Cars under !ic! Santro Uing, (lto and 4aganB represents individual ;bjects In t!is contexteac! Car ;bject ill !ave its on, 'odel, Vear o$ 'anu$acture, Color, Top Speed, Engine "oer etc,!ic! $or% "roperties o$ t!e Car class and t!e associated actions ie, object $unctions like Start, 'ove,and Stop $or% t!e 'et!ods o$ Car Class/o %e%ory is allocated !en a class is created 'e%ory isallocated only !en an object is created, ie, !en an instance o$ a class is createdI,'.*)(,6.#In!eritance is t!e process o$ $or%ing a ne class $ro% an existing class or base class T!ebase class is also knon as parent class or super class T!e ne class t!at is $or%ed is called derivedclass erived class is also knon as a c!ild class or sub class In!eritance !elps in reducing t!e overallcode sie o$ t!e progra%, !ic! is an i%portant concept in object-oriented progra%%ingD()( A8)(6)*5,# ata (bstraction increases t!e poer o$ progra%%ing language by creating userde$ined data types ata (bstraction also represents t!e needed in$or%ation in t!e progra% it!outpresenting t!e detailsD()( E,6(;:()*5,#

    ata Encapsulation co%bines data and $unctions into a single unit called Class 4!en using ataEncapsulation, data is not accessed directlyN it is only accessible t!roug! t!e $unctions present inside t!eclass ata Encapsulation enables t!e i%portant concept o$ data !iding possibleP5?5;'*?# "oly%orp!is% allos routines to use variables o$ di$$erent types at di$$erent ti%es (noperator or $unction can be given di$$erent %eanings or $unctions "oly%orp!is% re$ers to a single$unction or %ulti-$unctioning operator per$or%ing in di$$erent aysD,(?*6 B*,*,K inding re$ers to t!e linking o$ procedure call to t!e code to be executed in responseto t!e call yna%ic inding or )ate inding %eans t!at t!e code associated it! a given procedure callis knon only at t!e run-ti%eM.(. P(*,K ;bjects co%%unicate beteen eac! ot!er by sending and receiving in$or%ationknon as %essages ( %essage to an object is a re*uest $or execution o$ a procedure 'essage passinginvolves speci$ying t!e na%e o$ t!e object, t!e na%e o$ t!e $unction and t!e in$or%ation to be sent

    2%E@;(*, *,*,. /:,6)*5, *, .)(* :*, .@(?;.%

    (n inline $unction is a $unction t!at is expanded in line !en it is invoked T!e co%pilerBeplaces t!e $unction call it! corresponding $unction code T!e inline $uncitions are de$ined

    (s $ollosK *,*,. /:,6)*5,-'.(.

    F:,6)*5, 85

    E@(?;.#

    inline double cube1double a2 M

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    6/52

    Beturn1aaa2N OSo%e situations !ere inline expansion %ay not ork areK

    For $unctions returning values, i$ a loop , a sitc!, or a goto exists For $unctions not returning values, i$ a return state%ent exists I$ $unctions contain static variables I$ inline $unctions are recursive

    -Exa%ple progra% to illustrate inline $unctions KWinclude Xiostrea%!Linline $loat %ul1$loat x, $loat y2 M return1xy2N Oinline double div1double p, double *2 M return1pG*2 N Oint %ain1 2M $loat a38 N $loat b87N coutXX %ul1a,b2XX6Yn6N coutXX div1a,b2XX6Yn6N

    return 9NO3%D./*,. /:,6)*5, 57.5(*,%*). ( ;5(? )5 *:)(). *, .)(* :*, .@(?;.%

    ( single $unction na%e can be used to per$or% di$$erent types o$ tasks T!e sa%e $unction na%e canbe used to !andle di$$erent nu%ber and di$$erent types o$ argu%ents T!is is knon as $unctionoverloading or $unction poly%orp!is%

    WincludeXiostrea%!LWincludeXconio!Lvoid sap1int @x,int @y2Mint tN

    txNxyNytNOvoid sap1$loat @p,$loat @*2M$loat tNtpNp*N*tNOvoid sap1c!ar @c3,c!ar @c82

    Mc!ar tNtc3Nc3c8Nc8tNOvoid %ain12Mint i,jN

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    7/52

    $loat a,bNc!ar s3,s8Nclrscr12NcoutXXZYn Enter to integers K YnZNcoutXXZ i ZNcinLLiNcoutXXZYn j ZNcinLLjNsap1i,j2NcoutXXZYn Enter to $loat nu%bers K YnZNcoutXXZ a ZNcinLLaNcoutXXZYn b ZNcinLLbNsap1a,b2NcoutXXZYn Enter to C!aracters K YnZNcoutXXZ s3 ZNcinLLs3NcoutXXZYn s8 ZNcinLLs8Nsap1s3,s82NcoutXXZYn ($ter Sapping YnZNcoutXXZ Yn Integers i ZXXiXXZYt j ZXXjNcoutXXZ Yn Float /u%bers a ZXXaXXZYt b ZXXbNcoutXXZ Yn C!aracters s3 ZXXs3XXZYt s8 ZXXs8Ngetc!12NO

    4%E@;(*, 65,):6)5 (, D.):6)5 :*, (, .@(?;. ;5(?%

    Constructor $unction gets invoked !en an object o$ a class is constructed 1declared2 and destructor$unction gets invoked !en t!e object is destructed 1goes out o$ scope2

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    8/52

    ON

    void %ain1void2M%yclass aN

    coutXXaadd12NOExa%ple estructorGGExa%ple "rogra% in C++WincludeXiostrea%!L

    class %yclassMpublicK

    %yclass12McoutXXZdestructedYnZNOON

    void %ain1void2M%yclass objNcoutXXZinside %ainYnZNO

    %*). ( C++ ;5(? )5 ?:)*; )5 ?()*6. (, ;*,) )'. .:)%

    WincludeXiostrea%!LClass %atrixM"rivateK int a[7\[7\N"ublicK void get%atrix1int r, int c2Nvoid print%atrix1int r, int c2Nvoid %ul1%atrix,%atrix2NON#oid %atrixKKget%atrix1int r, int c2Mint I,jNcoutXX6Enter %atrix ele%ents6NFor1 i9NiXrNi++2For1j9NjXcNj++2CinLLa[i\[j\NO

    #oid %atrixKKprint%atrix1int r, int c2MInt I,jNFor1i9NiXrNi++2MFor1j9NjXcNj++2MCoutXX6 5XXa[i\[j\N

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    9/52

    OCoutXX6Yn6NOO#oid %atrixKK%ul1%atrix (, %atrix 2M'atrix CNInt I,j,kNr3(rN c3(cNr8rN c8cNFor1i9NiXr3Ni++2MFor1j9NjXc3Nj++2MCa[i\[j\9NFor1k9NkXc8Nk++2Mca[i\[j\Ca[i\[j\+(a[i\[k\a[k\[j\NOOO

    #oid %ain12M'atrix ([7\[7\,[7\[7\,C[7\[7\NInt r3,r8,c3,c8NCoutXX6enter order o$ 8 %atrices6NCinLLr3LLc3LLr8LLc8NTryMI$1r8c32M(read%atrix1r3,c32Nread%atrix1r8,c82NC%ul1(,2N(print%atrix1r3,c32Nprint%atrix1r8,c82NCprint%atrix1r3,c82NExit192NOelseM t!ro 1c82NOO

    Catc!1int x2MCoutXX6Invalid %atrix order6NOO

    O

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    10/52

    P ;nly existing operators can be overloadedP 4e cannot c!ange t!e basic %eaning o$ an operatorP T!e overloaded operator %ust !ave at least one operandP ;verloaded operators $ollo t!e syntax rules o$ t!e original operators-.eneral $or% o$ operator $unction isKR.):, );. 6(,(?. ## 5;.()5 5;-(*)

    F:,6)*5, 85

    ;verloaded operator $unctions can be invoked by expression x op y $or binary operatorsIn t!e $olloing progra% overloaded $unction is invoked !en t!e expression c3+c8 is encounteredT!is expression is t!e sa%e as operator 5;@ *. 5;.()5 +6$62

    using $riend $unctionWincludeXiostrea%!LWincludeXconio!Lclass co%plexMprivateK$loat realN$loat i%gNpublicKco%plex12Mreal99Ni%g99NOco%plex1$loat a,$loat b2MrealaNi%gbNO$riend co%plex operator +1co%plex,co%plex2Nvoid display12McoutXXZYnZXXrealXXZ+-iZXXi%gXXZYnZNOONco%plex operator +1co%plex c3,co%plex c82Mco%plex tNtrealc3real+c8realNti%gc3i%g+c8i%gN

    return1t2NOvoid %ain12Mclrscr12Nco%plex c31AA,8A2Nco%plex c813A,AA2Nco%plex c7N

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    11/52

    c7c3+c8Nc3display12Nc8display12Nc7display12Ngetc!12NO

    UNIT-II PART-A

    $%'() (. )'. 6++ 5;.()5 )'() 6(,,5) 8. 57.5(.1

    Sie operator 1sieo$2Scope resolution operator 1KK2%e%ber access operators1 , 2Conditional operator 1JK22% '() * ( 7*):( 8(. 6(1

    4!en a class is declared as virtual c++ takes care to see t!at only copy o$ t!at class is in!erited,regardless o$ !o %any in!eritance pat!s exist beteen t!e virtual base class and a derived class3% '() * )'. *//..,6. 8.).., 8(. 6( (, .*7. 6(1

    T!e biggest di$$erence beteen t!e base class and t!e derived class is t!at t!e derived class contains t!edata %e%bers o$ bot! t!e base and its on data %e%bers T!e ot!er di$$erence is based on t!e visibility%odes o$ t!e data %e%bers4% '() (. )'. :. 57.,*, )'. .6(()*5, 5/ ( 6( 5/ ?:)*;. *,'.*)(,6.1

    P 'ore t!an one class na%e s!ould be speci$ied a$ter t!e K sy%bolP #isibility %odes %ust be taken care o$I$ several in!eritance pat!s are e%ployed $or a single derived class t!e base class %ust be appropriatelydeclared% M.,)*5, )'. );. 5/ *,'.*)(,6.%

    3Single in!eritance8 'ultiple in!eritance7 &ierarc!ical in!eritance> 'ultilevel in!eritanceA &ybrid in!eritance

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    12/52

    MGGGGclass %e%ber speci$icationGGit! anony%ous type TGG!erever appropriateGGON$$% L*) )'. *, 5/ .@6.;)*5,%

    Exceptions are o$ to kinds na%elyP Sync!ronous exceptionsP (sync!ronous exceptions$2% '() (. )'. .5 *, ,6'5,5: );. .@6.;)*5,1

    Errors suc! as 5out-o$-range index6 and 5over-$lo6 belong to t!e sync!ronous type exceptions$3% '() (. )'. .5 *, (,6'5,5: );. .@6.;)*5,1

    T!e errors t!at are caused by errors beyond t!e control o$ t!e progra% 1suc! as keyboard interrupts2 arecalled async!ronous exceptions$4% '() (. )'. )( )'() (. ;./5?. 8 )'. .5 '(,*, ?.6'(,*?1

    T!e %ec!anis% suggests a separate error !andling code t!at per$or%s t!e $olloing tasksK32 Find t!e proble% 1&it t!e exception282 In$or% t!at an error !as occurred 1T!ro t!e exception272 Beceive t!e error in$or%ation 1Catc! t!e exception2>2 Take corrective actions 1&andle t!e exception2$% M.,)*5, )'. . 5 :. *, .@6.;)*5, '(,*,%

    T!e keyords used in exception !andling areP t!roP tryP catc!$% M.,)*5, )'. .:*6(.,) *5 /:,6)*5, /5 ?(,*;:()5'anipulator E*uivalent ios $unctionset1int 2 idt!12

    setprecision1int d2 precision12set$ill1int c2 $ill12setios$lags1long $2 set$12resetios$lags1long $2 unset$12endl 5Yn6$9% D./*,. /* /:,6)*5,%

    T!e $ill1 2 $unction can be used to $ill t!e unused positions o$ t!e $ield by any desired c!aracter rat!ert!an by !ite spaces 1by de$ault2 It is used in t!e $olloing $or%K

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    13/52

    cout$ill1c!2N!ere c! represents t!e c!aracter !ic! is used $or $illing t!e unused positions For exa%ple, t!estate%entscout$ill1]2Ncoutidt!1392NcoutXXA8A9XX6Yn6Nill produce t!e $olloing outputK20 %G*7. )'. ,)(@ 5/ .@6.;)*5, '(,*, ?.6'(,*?%

    T!e syntax o$ exception !andling %ec!anis% is as $ollosKtryM---------------------t!ro exception---------------------Ocatc!1type argu%ents2M------------------------------------------O--------------------------------------------

    PART B

    $%E@;(*, D*//..,6. );. 5/ *,'.*)(,6. *)' :*)(8. 6++ 65*,%

    In!eritance is t!e process by !ic! objects o$ one class ac*uire t!e properties o$ objects o$ anot!erclass It supports t!e concept o$ !ierarc!ical classi$ication and provides t!e idea o$ reusability T!eclass !ic! is in!erited is knon as t!e base or super class and class !ic! is nely derived is knonas t!e derived or sub classT!e syntax o$ deriving a ne class $ro% an already existing class is given by,class derived-class K visibility-%ode base-classMbody o$ derived classOT!e various types o$ in!eritance are,P Single in!eritance K In single in!eritance, one class is derived $ro% an already existing base classP 'ulti-level in!eritance K In %ulti-level in!eritance, a ne class is derived $ro% a class alreadyderived $ro% t!e base classP 'ultiple in!eritance K In %ultiple in!eritance, a single class is derived $ro% %ore t!an one baseclassP &ierarc!ical in!eritance K In !ierarc!ical in!eritance, %ore t!an one class is derived $ro% a singlebase classP &ybrid in!eritance K &ybrid in!eritance is de$ined as a co%bination o$ %ore t!an one in!eritanceExa%ple K'

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    14/52

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    15/52

    WincludeXconio!Lte%plateXclass TLT s*r1T @ n2Mreturn1nn2NOvoid %ain12Mint aN$loat bNdouble cNclrscr12NcoutXXZYnYn Enter an Integer K ZNcinLLaNcoutXXZYn S*uare o$ a ZXXs*r1a2XXendlNcoutXXZYnYn Enter a Float #alue K ZNcinLLbNcoutXXZYn S*uare o$ b ZXXs*r1b2XXendlNcoutXXZYnYn Enter a ouble #alue K ZNcinLLcNcoutXXZYn S*uare o$ c ZXXs*r1c2Ngetc!12NO

    3% E@;(*, F*. H(,*, *, C++%N57D.6 20$0 A;*M( 20$$

    Files are re*uired to save our data $or $uture use, as Ba% is not able to !old our dataper%anently

    T!e )anguage like CGC++ treat every t!ing as a $ile , t!ese languages treat keyboard , %ouse, printer,&ard disk , Floppy disk and all ot!er !ardare as a $ile

    T!e asic operation on textGbinary $iles are K BeadingGriting ,reading and %anipulation o$ data stored

    on t!ese $iles ot! types o$ $iles needs to be open and close

    H5 )5 5;., F*.

    U*, ?.?8. /:,6)*5, O;., U*, C5,):6)5

    Files

    Program FilesData Files

    Text Files Binary Files

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    16/52

    Syntax

    Filestrea% objectN

    ;bjectopen15$ilena%e6,%ode2N

    Exa%ple

    i$strea% $inN

    $inopen15abctxt62

    Syntax

    Filestrea%object15$ilena%e6,%ode2N

    Exa%ple

    i$strea% $in15abctxt62N

    'ode are optional and given at t!e end

    Filena%e %ust $ollo t!e convention o$ ^7 and its extension can be anyone

    H5 )5 65. /*.

    "rogra%

    "rogra% (Ctxt $ile contents

    WincludeX$strea%Lusing na%espace stdNint %ain12M o$strea% $outN $outopen1ZabctxtZ2N

    $outXXZT!is is %y $irst progra% in $ile !andlingZN $outXXZYn &ello againZN $outclose12N return 9NO

    T!is is %y $irst progra% in $ile !andling&ello again

    All types of files can be closed using close( ) member function

    Syntax

    fileobject.close( )

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    17/52

    includeX$strea%LWincludeXiostrea%LWincludeXconio!Lusing na%espace stdNint %ain12M i$strea% $inN c!ar str[^9\N $inopen1ZabctxtZ2N $inLLstrN GG read only $irst GGstring $ro% $ile

    coutXXZYn Fro% File KZXXstrN GG as GGspaces istreated as ter%ination point getc!12N return 9NO/;TE K To overco%e t!is proble% use

    $ingetline1str,:_2N

    etecting E/ ;F FI)E

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    18/52

    WincludeX$strea%LWincludeXconio!LWincludeXiostrea%Lusing na%espace stdNint %ain12M c!ar str[399\N

    i$strea% $inN $inopen1ZcKYYabctxtZ2N !ile1$ineo$122 M $ingetline1str,__2N coutXXstrN O $inclose12N getc!12N return 9NO

    WincludeX$strea%LWincludeXconio!LWincludeXiostrea%Lusing na%espace stdNint %ain12M c!ar c!N

    i$strea% $inN $inopen1Z$ile=cppZ2N !ile1$ineo$122 M $inget1c!2N coutXXc!N O $inclose12N getc!12N return 9NO

    4% E@;(*, (85:) E@6.;)*5, '(,*, *, C++%N57D.6 20$0

    Exceptions are run ti%e ano%alies T!ey include conditions like division by ero oraccess to an array outside to its bound etcTypesK Sync!ronous exception (sync!ronous exception

    Find t!e proble% 1 &it t!e exception 2 In$or% t!at an error !as occurred 1T!ro exception2 Beceive error in$or%ation 1Catc! exception2 Take corrective action 1&andle exception2

    C++ exception !andling %ec!anis% is basically built upon t!ree keyords, na%ely, ) )'5and 6()6'% T!e keyord try is used to pre$ace a block o$ state%ents !ic! %ay generateexceptions T!is block o$ state%ents is knon as try block 4!en an exception is detected it ist!ron using a t!ro state%ent in t!e try block ( catc! block de$ined by t!e keyord catc! catc!est!e

    try block t!roing an exception invoking $unction t!at generates exception t!roing %ec!anis% catc!ing %ec!anis% %ultiple catc! state%ents catc! all exceptions Bet!roing an exception

    G.,.( /5?

    try M t!ro exceptionN

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    19/52

    O Catc! 1 type arg2 M O E@6.;)*5, )'() '( )5 8. 6(:') '., /:,6)*5, (. :.- T'. /5? * ( /55#

    Type $unction 1arg list2 M T!ro 1object2 O try M Invoke $unction !ereN

    O Catc! 1 type arg2 M &andles exception !ere O

    M:)*;. 6()6' )().?.,)K

    try M t!ro exceptionN

    O Catc! 1 type arg2 M GG catc! block3 O

    Catc! 1 type arg2 M GGcatc! block8 O

    Catc! 1 type arg2 M GGcatc! block n O

    G.,.*6 .@6.;)*5, '(,*, * 5,. :*, .*;. ( /55#

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    20/52

    Catc! 1 2 M O

    AI:)(). 7*):( /:,6)*5, (, ;:. 7*):( /:,6)*5, *)' :*)(8. .@(?;.1V*):( F:,6)*5,#

    WincludeXiostrea%!LWincludeXconio!L

    class abcM

    protected Kint a,bN

    publicKvoid take12McoutXXZYnEnter to RintR valuesKKZNcinLLaLLbNOvirtual void display129NONclass xyKpublic abc

    MpublicKvoid display12McoutXXZYnSu% $or 3st derived classZXOONclass %nKpublic abcM

    publicKvoid display12McoutXXZYnSu% $or 8nd derived classKZX

    OONvoid %ain12Mclrscr12Nxy obN%n ob3Nabc ptrN

    ptr@obNcoutXXZYnFor object o$ 3st derived classZX

    ptr-Ltake12Nptr-Ldisplay12NcoutXXZYnFor object o$ 8nd derived classZX

    ptr@ob3Nptr-Ltake12Nptr-Ldisplay12Ngetc!12NO

    P:. V*):( F:,6)*5,#

    ( virtual $unction body is knon as "ure #irtual Function In above exa%ple e can see t!at t!e $unction isbase class never gets invoked In suc! type o$ situations e can use pure virtual $unctions

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    21/52

    Exa%ple K sa%e exa%ple can re-rittenclass baseM

    publicKvirtual void s!o129N GGpure virtual $unctionON

    class derived3 K public base

    MpublicKvoid s!o12McoutXXZYn erived 3ZNOON

    class derived8 K public baseM

    publicKvoid s!o12McoutXXZYn erived 8ZNOON

    void %ain12M

    base bN derived3 d3N derived8 d8Nb @d3Nb-Ls!o12Nb @d8Nb-Ls!o12NO

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    22/52

    Mc!ar branc![89\N

    publicKvoid get12McinLLregnoLLna%eLLbranc!NOvoid put12

    McoutXXregnoXXna%eXXbranc!NONclass %edicalK public studentMMc!ar branc![89\N

    publicKvoid get12McinLLregnoLLna%eLLbranc!NOvoid put12McoutXXregnoXXna%eXXbranc!NONvoid %ain12Mengineering eKeget12Neput12Nscience sNsget12Nsput12N%edical %N%get12N%put12N

    O

    UNIT-III

    PART-A

    $%*). 5, )'. ./*,*)*5, 5/ ()( ):6):.1

    ( data structure is a %at!e%atical or logical ay o$ organiing data in t!e %e%ory t!at consider notonly t!e ite%s stored but also t!e relations!ip to eac! ot!er and also it is c!aracteried by accessing$unctions

    2% G*7. /. .@(?;. /5 ()( ):6):.1Stacks, 0ueue, )inked list, Trees, grap!s3% D./*,. A5*)'?1

    (lgorit!% is a solution to a proble% independent o$ progra%%ing language It consist o$ set o$ $initesteps !ic!, !en carried out $or a given set o$ inputs, produce t!e corresponding output and ter%inatein a $inite ti%e4% '() (. )'. /.():. 5/ (, .//*6*.,) (5*)'?1

    P Free o$ a%biguity

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    23/52

    P E$$icient in execution ti%eP Concise and co%pactP Co%pletenessP e$initenessP Finiteness% L*) 5, (, /5: (;;*6()*5, 5/ ()( ):6):.1

    Co%piler design;perating Syste%atabase 'anage%ent syste%/etork analysis

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    24/52

    P ` "% '() * ( :.:.1

    ( 0ueue is an ordered collection o$ ite%s $ro% !ic! ite%s %ay be deleted atone end called t!e $ront o$ t!e *ueue and into !ic! te%s %ay be inserted att!e ot!er end called rear o$ t!e *ueue0ueue is called as Firstin-First-;ut1FIF;2$9% '() * ( P*5*) :.:.1

    "riority *ueue is a data structure in !ic! t!e intrinsic ordering o$ t!e ele%ents does deter%ine t!eresults o$ its basic operations (scending and escending priority *ueue are t!e to types o$ "riority*ueue20% '() * ( *,. *)1

    )inked list is a kind o$ series o$ data structures, !ic! are not necessarily adjacent in %e%ory Eac!structure contain t!e ele%ent and a pointer to a record containing its successor2$% '() * ( 5:8 *,. *)1

    In a si%ple linked list, t!ere ill be one pointer na%ed as R/EUT ";I/TEBR to point t!e next ele%ent,!ere as in a doubly linked list, t!ere ill be to pointers one to point t!e next ele%ent and t!e ot!er topoint t!e previous ele%ent location22% D./*,. 5:8. 6*6:( *,. *)1

    In a doubly linked list, i$ t!e last node or pointer o$ t!e list, point to t!e $irst ele%ent o$ t!e list,t!en it isa circularly linked list23% '() * ( 6*6:( :.:.1

    T!e *ueue, !ic! raps around upon reac!ing t!e end o$ t!e array is called as circular *ueue24% D./*,. ?(@ (, ?*, '.(;1

    ( !eap in !ic! t!e parent !as a larger key t!an t!e c!ildRs is called a %ax !eap( !eap in !ic! t!e parent !as a s%aller key t!an t!e c!ild is called a %in !eap PART B

    $% E@;(*, *)' .@(?;. )'. *,.)*5, & ..)*5, *, 5:8 *,. *)

    D5:8 L*,. L*)( oubly linked list is a linked list in !ic! eac! node !as t!ree $ields na%ely data $ield, $orard link1F)I/D2 and ackard )ink 1)I/D2 F)I/D points to t!e successor node in t!e list !ereas )I/Dpoints to t!e predecessor nodeSTRUCTURE DECLARATION # -Struct /odeMint Ele%entNStruct /ode F)I/DNStruct /ode )I/DONROUTINE TO INSERT AN ELEMENT IN A DOUBL LIN"ED LISTvoid Insert 1int U, list ), position "2MStruct /ode /enodeN/enode %alloc 1sie o$ 1Struct /ode22N

    I$ 1/enode /

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    25/52

    OROUTINE TO DELETE AN ELEMENTvoid elete 1int U, )ist )2Mposition "N" Find 1U, )2NI$ 1 Is)ast 1", )22MTe%p "N" -Llink -LFlink /

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    26/52

    position /ext NONROUTINE TO INSERT AN ELEMENT IN THE LISTvoid Insert 1int U, )ist ), "osition "2G Insert a$ter t!e position "GMposition /enodeN/enode %alloc 1sie o$ 1Struct /ode22NI$ 1/enode /

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    27/52

    " ) -L/extN!ile 1"-L/ext /

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    28/52

    T!e $unda%ental operations per$or%ed on a stack are3 "us!8 "opPUSH #T!e process o$ inserting a ne ele%ent to t!e top o$ t!e stack For every pus! operation t!e top isincre%ented by 3POP #T!e process o$ deleting an ele%ent $ro% t!e top o$ stack is called pop operation ($ter every popoperation t!e top pointer is decre%ented by 3E!CEPTIONAL CONDITIONS

    O7.F5

    (tte%pt to insert an ele%ent !en t!e stack is $ull is said to be over$loU,.F5

    (tte%pt to delete an ele%ent, !en t!e stack is e%pty is said to be under$loA( I?;.?.,)()*5,5/ )(6In t!is i%ple%entation eac! stack is associated it! a pop pointer, !ic! is -3 $or an e%pty stackP To pus! an ele%ent U onto t!e stack, Top "ointer is incre%ented and t!en set Stack [Top\ UP To pop an ele%ent, t!e stack [Top\ value is returned and t!e top pointer is decre%entedP pop on an e%pty stack or pus! on a $ull stack ill exceed t!e array boundsvoid pus! 1int x, Stack S2Mi$ 1IsFull 1S22Error 1ZFull StackZ2NelseMTop Top + 3NS[Top\ UNOOint IsFull 1Stack S2Mi$ 1Top (rraysie2return 132NOROUTINE TO POP AN ELEMENT FROM THE STAC"void pop 1Stack S2Mi$ 1IsE%pty 1S22Error 1ZE%pty StackZ2NelseMU S [Top\NTop Top - 3NO

    Oint IsE%pty 1Stack S2Mi$ 1S Top -32return 132NOROUTINE TO RETURN TOP ELEMENT OF THE STAC"int TopEle%ent 1Stack S2

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    29/52

    Mi$ 1 IsE%pty 1s22return S[Top\NelseError 1ZE%pty StackZ2Nreturn 9NO

    % *). ( ;56.:. )5 *,.) & ..). ( ..?.,) *, )'. *,. *) *?;.?.,)()*5, 5/ )(6

    LIN"ED LIST IMPLEMENTATION OF STAC"P "us! operation is per$or%ed by inserting an ele%ent at t!e $ront o$ t!e listP "op operation is per$or%ed by deleting at t!e $ront o$ t!e listP Top operation returns t!e ele%ent at t!e $ront o$ t!e liststruct nodeMint dataNstruct node linkNONstruct node cur,$irstN

    void create12Nvoid pus!12Nvoid pop12Nvoid display12N

    void create12Mprint$1ZYnE/TEB T&E FIBST E)E'E/TK Z2Ncur1struct node 2%alloc1sieo$1struct node22Nscan$1ZHdZ,@cur-Ldata2Ncur-Llink/

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    30/52

    void pop12Mi$1$irst/

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    31/52

    Mi$ 1Front X 92print 1Z 0ueue

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    32/52

    void pop12Mi$1$irst/% *). '5) ,5). 5, 6:5 *?;.?.,)()*5, *)' .@(?;.%

    Cursor i%ple%entation is very use$ul !ere linked list concept !as to be i%ple%ented it!out usingpointersC5?;(*5, 5, P5*,). I?;.?.,)()*5, (, C:5, I?;.?.,)()*5, 5/ L*,. L*)%

    P5*,). I?;.?.,)()*5, C:5 I?;.?.,)()*5,3 ata are stored in a collection o$ structures ata are stored in a global array Eac! structure contains adata and next structures &ere array index is pointer considered as an addressP5*,). I?;.?.,)()*5, C:5 I?;.?.,)()*5,8 'alloc $unction is used to create a node and It %aintains a list o$ $ree cells called $ree $unction is usedto released t!e cell cursors space in !ic! slot 9 is considered as a !eader and /ext is e*uivalent to t!epointer !ic! points to t!e next slotROUTINE TO DELETE AN ELEMENTvoid elete 1int U, )ist )2Mposition ", te%pN" Findprevious 1U, )2Ni$ 1 Is)ast 1", )22Mte%p CursorSpace ["\/extNCursorSpace ["\/ext CursorSpace [te%p\/extNCursorFree 1te%p2NOOROUTINE FOR INSERTIONvoid Insert 1int U, )ist ), position "2Mposition nenodeNnenode Cursor(lloc 1 2Ni$ 1nenode 92CursorSpace [nenode\Ele%ent UN

    CursorSpace [nenode\ /ext CursorSpace ["\/extNCursorSpace ["\/ext nenodeNO

    9% E7(:(). )'. /55*, ;5)/*@ .@;.*5,

    (86+.+/+ '.. (=3 8=2 6= =< .= > /=2

    Bead t!e post$ix expression one c!aracter at a ti%e until it encounters t!e deli%iter QWRStep 3 K - I$ t!e c!aracter is an operand, pus! its associated value onto t!e stack

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    33/52

    Step 8 K - I$ t!e c!aracter is an operator, ";" to values $ro% t!e stack, apply t!e operator tot!e% and pus! t!e result onto t!e stack(ns3^=

    $0% *). (, (5*)'? /5 65,7.) *,/*@ .@;.*5, )5 ;5)/*@ .@;.*5, *)' (, .@(?;. 5/

    A+BC-DEFGH%$ K I$ t!e c!aracter is a rig!t paraent!esis, pop all t!e operators $ro% t!e stack till itencounters le$t parent!esis, discard bot! t!e parent!esis in t!e output"ost$ix ExpressionK(CEFG.-&+

    UNIT IV

    PART A

    $% D./*,. ,5,-*,.( ()( ):6):.1

    ata structure !ic! is capable o$ expressing %ore co%plex relations!ip t!an t!at o$ p!ysical adjacencyis called non-linear data structure2% D./*,. )..1

    ( tree is a data structure, !ic! represents !ierarc!ical relations!ip beteen individual ata ite%s3%D./*,. 6'* (, ;(.,) 5/ ( )..%

    T!e root o$ eac! subtree is said to be a c!ild o$ ]r and ]r is t!e parent o$ eac! subtree root4% D./*,. .(/1

    In a directed tree any node !ic! !as out degree o is called a ter%inal node or a lea$% '() * ( B*,( )..1

    ( inary tree is a $inite set o$ ele%ents t!at is eit!er e%pty or is partitioned into t!ree disjoint subsetsT!e $irst subset contains a single ele%ent called t!e root o$ t!e tree T!e ot!er to subsets are t!e%selvesbinary trees called t!e le$t and rig!t sub trees

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    34/52

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    35/52

    P.5. T(7.(T!e preorder traversal o$ a binary tree is per$or%ed as $ollos, #isit t!e root Traverse t!e le$t subtree in preorder Traverse t!e rig!t subtree in preorderRECURSIVE ROUTINE FOR PREORDER TRAVERSALvoid "reorder 1Tree T2Mi$ 1T / to : $or eac! c!aracter in t!e expressiontill t!e deli%iter

    Step >K I$ t!e c!aracter is an operand, place it on to t!e output

    Step AK I$ t!e c!aracter is an operator, t!en c!eck t!e Stack operator !as a !ig!er or e*ual priority t!ant!e input operator t!en pop t!at operator $ro% t!e stack and place it onto t!e output Bepeat t!is till t!ereis no !ig!er priority operator on t!e top o$ t!e Stack and pus! t!e input operator onto t!e Stack

    Step =K I$ t!e c!aracter is a le$t parent!esis, pus! it onto t!e Stack

    Step :K I$ t!e c!aracter is a rig!t parent!esis, pop all t!e operators $ro% t!e Stack till it encounters le$tparent!esis iscard bot! t!e parent!esis in t!e output

    Step ^K Ter%inate t!e execution

    RECURSIVE ROUTINE FOR INORDER TRAVERSALvoid Inorder 1Tree T2

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    36/52

    Mi$ 1T /

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    37/52

    !ile11c!getc1stdin22RYnR2M

    Expr[%\c!N%++N

    Ol%Nin$ix`to`post$ix12Ngetc!12N

    O

    void pus!1c!ar c!2M

    i$1Top+3 L SIE2M

    print$1ZYnStack is $ullZ2NOelse

    MTopTop+3NStack[Top\ c!N

    OO

    void pop12M

    i$ 1Top X 92M

    print$1ZYn Stack is e%ptyZ2NOelseM

    i$1Top L92M

    i$1Stack[Top\R1R2print$1ZHcZ,Stack[Top\2N

    TopTop-3NO

    O

    O

    void in$ix`to`post$ix12M

    %9N!ile1%Xl2M

    sitc!1Expr[%\2

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    38/52

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    39/52

    i$1isalp!a1Expr[%\22M

    print$1ZHcZ,Expr[%\2N++%NbreakN

    OelseM

    print$1ZYn So%e errorZ2Nexit192N

    OO

    OO

    3%N((). )'. 5;.()*5, 5/ B*,( .(6' ).. 5, .(6'*, ( ,5. I,.)*5, ,5. (,

    ..)*5, ,5. /5? 8*,( ).. *)' .@(?;.%$

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    40/52

    Oreturn tN

    O4%'() (. AVL )..1 E@;(*, *, .)(* )'. AVL 5)()*5,%

    AVL T.. # - A.5, - V.* (, LANDIS(n (#) tree is a binary searc! tree except t!at $or every node in t!e tree, t!e !eig!t o$ t!e le$t and rig!tsubtrees can di$$er by at%ost 3 T!e !eig!t o$ t!e e%pty tree is de$ined to be - 3

    ( balance $actor is t!e !eig!t o$ t!e le$t subtree %inus !eig!t o$ t!e rig!t subtree For an (#) tree allbalance $actor s!ould be +3, 9, or -3 I$ t!e balance $actor o$ any node in an (#) tree beco%es less t!an-3 or greater t!an 3, t!e tree !as to be balanced by %aking eit!er single or double rotations(n (#) tree causes i%balance, !en any one o$ t!e $olloing conditions occur

    Case 3 K (n insertion into t!e le$t subtree o$ t!e le$t c!ild o$ node Case 8 K (n insertion into t!e rig!t subtree o$ t!e le$t c!ild o$ node Case 7 K (n insertion into t!e le$t subtree o$ t!e rig!t c!ild o$ node Case > K (n insertion into t!e rig!t subtree o$ t!e rig!t c!ild o$ node

    T!ese i%balances can be overco%e by3 Single Botation8 ouble BotationS*,. R5)()*5,

    Single Botation is per$or%ed to $ix case 3 and case >Case 3 (n insertion into t!e le$t subtree o$ t!e le$t c!ild o$ D8Single Botation to $ix Case 3ROUTINE TO PERFORM SINGLE ROTATION ITH LEFTSingleBotateit!)e$t 1"osition D82M"osition D3ND3 D8-L)e$t ND8-Lle$t D3-LBig!t ND3-LBig!t D8ND8-L&eig!t 'ax 1&eig!t 1D8-L)e$t2, &eig!t 1D8-L Big!t22 + 3 ND3-L&eig!t 'ax 1&eig!t 1D3-Lle$t2, &eig!t 1D3-LBig!t22 + 3N

    return D3NOS*,. R5)()*5, )5 /*@ C(. 4 #-Case > K - (n insertion into t!e rig!t subtree o$ t!e rig!t c!ild o$ D3ROUTINE TO PERFORM SINGLE ROTATION ITH RIGHT #-Single Botation 4it! Big!t 1"osition D82M"osition D8ND8 D3-L Big!tND3 -LBig!t D8-L)e$t ND8-L)e$t D3ND8-L&eig!t 'ax 1&eig!t 1D8-L)e$t2, &eig!t 1D8-LBig!t22 +3 N

    D3-L&eig!t 'ax 1&eig!t 1D3-L)e$t2, &eig!t 1D3-LBig!t22 +3 NBeturn D8NOSingle Botation it! le$t 1D72D5:8. R5)()*5,ouble Botation is per$or%ed to $ix case 8 and case 7Case 8 K(n insertion into t!e rig!t subtree o$ t!e le$t c!ildROUTINE TO PERFORM DOUBLE ROTATION ITH LEFT #

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    41/52

    ouble Botate it! le$t 1"osition D72M G Botation eteen D3@ D8GD7-L)e$t Single Botate it! Big!t 1D7-L)e$t2NG Botation eteen D7@ D8GBeturn Single Botate 4it! )e$t 1D72NOC(. 4 #

    (n Insertion into t!e le$t subtree o$ t!e rig!t c!ild o$ D3ROUTINE TO PERFORM DOUBLE ROTATION ITH RIGHT #ouble Botate it! Big!t 1"osition D32MG Botation eteen D8@ D7GD3-L Big!t Single Botate 4it! )e$t 1D3-L Big!t2NG Botation eteen D3@ D8Greturn Single Botate 4it! Big!t 1D32N

    %E@;(*, *)' (5*)'? '5 *,.)*5, (, ..)*5, * ;./5?. *, ( AVL )..% E@;(*, '5

    )'. ).. * 8((,6. (/). )'. 5;.()*5,%$

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    42/52

    elsetdoublerotationit!rig!t1t2N

    OOt-L!eig!t%ax1!eig!t1t-Lle$t2,!eig!t1t-Lrig!t22+3Nreturn tN

    ODELETION ROUTINE

    eletion is sa%e as binary searc! tree ($ter deleting t!e ele%ent e !ave to c!eck t!e balance $actor o$t!e tree I$ it is un balanced ,do suitable rotations to %ake t!e tree balanced

    UNIT V

    PART A

    $% '() * ?.(,) 8 5)*,1

    ;rdering t!e data in an increasing or decreasing $as!ion according to so%e relations!ip a%ong t!e dataite% is called sorting2% '() (. )'. )5 ?(*, 6(*/*6()*5, 5/ 5)*, 8(. 5, )'. 5:6. 5/ ()(1

    a Internal sortingb External sorting3% '() * ?.(,) 8 .@).,( 5)*,1

    External sorting is a process o$ sorting in !ic! large blocks o$ data stored in storage evices are %ovedto t!e %ain %e%ory and t!en sorted4% '() * ?.(,) 8 *,).,( 5)*,1

    Internal sorting is a process o$ sorting t!e data in t!e %ain %e%ory% '() (. )'. 7(*5: /(6)5 )5 8. 65,*.. *, .6**, ( 5)*, (5*)'?1

    a "rogra%%ing ti%eb Execution ti%e o$ t!e progra%c 'e%ory needed $or progra% environ%ent

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    43/52

    P Space Co%plexityP Ti%e Co%plexity$3% '() * ;./5?(,6. (,(* 5/ (, (5*)'?1

    T!e analysis o$ t!e per$or%ance o$ an algorit!% based on speci$ication is calledper$or%ance analysis It is loosely divided intoa "riori esti%atesb "osterior Testing$4% D./*,. ;(6. 65?;.@*)%

    Space co%plexity o$ an algorit!% is t!e a%ount o$ %e%ory it needs to run toco%pletion$% D./*,. )*?. 65?;.@*)%

    Ti%e co%plexity is t!e a%ount o$ co%puter ti%e an algorit!% re*uires to runto co%pletion$% '() * *7*. (, 65,:. ).6',*:.1

    ivide and Con*uer algorit!% is based on dividing t!e proble% to be solvedinto several, s%aller sub instances, solving t!e% independently and t!en co%biningt!e sub instances solutions so as to yield a solution $or t!e original instance$9% '() * ,(?*6 ;5(??*,1

    yna%ic progra%%ing algorit!% is a general class o$ algorit!%s !ic! solveproble%s by solving s%aller versions o$ t!e proble%, saving t!e solutions to t!es%all proble%s and t!en co%bining t!e% to solve t!e larger proble%s20% D./*,. G.. ?.)'5%

    T!e greedy %et!od suggests t!at one can devise an algorit!% t!at orks in stages, considering one inputat a ti%e (t eac! stage, a decision is %ade regarding !et!er a particular input is an opti%al solution(n exa%ple $or solution using greedy %et!od is ]knapsack proble%2$%L*) 5?. (5*)'? :. D,(?*6 P5??*,%

    'atrix-c!ain %ultiplication;pti%al inary Searc! Tree9-3knapsack proble%(ll-pairs S!ortest "at!22%L*) 5?. (5*)'? :. G.. (;;5(6'%

    ijikistras algorit!%s,"ri%s algorit!%s ,Druskals algorit!%s23%'() * ('.5) (5 6(.1

    S!ellsort is also called as di%inis!ing incre%ent sort24%'() * )'. 8(*6 )(). 5/ ?.. 5)1'ergesort is t!e tec!ni*ue !ic! !as sorted subarrays !ic! are %erged to $or% a single sorted array2%'() (. )'. ).6',*:. :. )5 6'55. )'. ;*75) ..?.,) /5 :*65)1

    T!e various tec!ni*ues are First ele%ent,Bando% pick 'edian o$ t!ree portioning2

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    44/52

    T!ree pointers are used in %ergesort ](ptr $or t!e $irst sorted subarray,ptr $or t!e second sortedsubarray and ]cptr $or t!e %erged sorted subarray

    PART B

    $% D./*,. H.(; S5) % *). )'. (5*)'? /5 '.(; 5) ;56.:.%

    &eap Sort

    &eap sort operates by $irst converting t!e list in to a !eap tree &eap tree is a binary tree in !ic! eac!node !as a value greater t!an bot! its c!ildren 1i$ any2 It uses a process called Zadjust to acco%plis! itstask 1building a !eap tree2 !enever a value is larger t!an its parent T!e ti%e co%plexity o$ !eap sort is;1nlogn2

    (lgorit!%K3 Construct a binary treeP T!e root node corresponds to ata[9\P I$ e consider t!e index associated it! a particular node to be i, t!en t!e le$t c!ild o$ t!is nodecorresponds to t!e ele%ent it! index 8i+3 and t!e rig!t c!ild corresponds to t!e ele%ent it! index8i+8 I$ any or bot! o$ t!ese ele%ents do not exist in t!e array, t!en t!e corresponding c!ild node doesnot exist eit!er8 Construct t!e !eap tree $ro% initial binary tree using ZadjustZ process7 Sort by sapping t!e root value it! t!e loest, rig!t %ost value and deleting t!e loest, rig!t %ostvalue and inserting t!e deleted value in t!e array in it proper position

    2% E@;(*, S'. S5) A5*)'? *)' .@(?;.%

    T!e idea o$ S!ellsort is t!e $olloingKa arrange t!e data se*uence in a to-di%ensional arrayb sort t!e colu%ns o$ t!e array

    T!e e$$ect is t!at t!e data se*uence is partially sorted T!e process above is repeated, but eac! ti%e it!a narroer array, ie it! a s%aller nu%ber o$ colu%ns In t!e last step, t!e array consists o$ only onecolu%n In eac! step, t!e sortedness o$ t!e se*uence is increased, until in t!e last step it is co%pletelysorted &oever, t!e nu%ber o$ sorting operations necessary in eac! step is li%ited, due to t!epresortedness o$ t!e se*uence obtained in t!e preceding steps

    Exa%pleK )et7 : _ 9 A 3 = ^ > 8 9 = 3 A : 7 > _ ^ 8 be t!e data se*uence to be sorted First, it is arranged in an array it! : colu%ns 1le$t2, t!en t!e colu%ns are sorted 1rig!t2K

    S!ellsort is one o$ t!e oldest sorting algorit!%s, na%ed a$ter its inventor ) S!ell13_A_2 It is $ast, easy to understand and easy to i%ple%ent &oever, its co%plexityanalysis is a little %ore sop!isticated

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    45/52

    7A:9=_8

    8

    3

    >=^_937>A:^987A=:_3

    7 : _ 9 A 3 =^ > 8 9 = 3 A: 7 > _ ^ 8

    7 7 8 9 A 3 A: > > 9 = 3 =^ : _ _ ^ 8

    ata ele%ents ^ and _ !ave no already co%e to t!e end o$ t!e se*uence, but a s%all

    ele%ent 182 is also still t!ere In t!e next step, t!e se*uence is arranged in 7 colu%ns,!ic! are again sortedK

    9A>3

    :

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    46/52

    8>=^_

    /o t!e se*uence is al%ost co%pletely sorted 4!en arranging it in one colu%n in t!elast step, it is only a =, an ^ and a _ t!at !ave to %ove a little bit to t!eir correct position

    void s!ellsort 1int[\ a, int n2Mint i, j, k, !, vN

    int[\ cols M37_37:=, >=7:_8, 3_^:=^, ^=_=3, 77_7=, 37::=, >A_8,

    3_=^, ^=3, 77=, 338, >^, 83, :, 7, 3O

    $or 1k9N kX3=N k++2

    M

    !cols[k\N

    $or 1i!N iXnN i++2

    Mva[i\N

    jiN!ile 1jL! @@ a[j-!\Lv2

    Ma[j\a[j-!\N

    jj-!N

    O

    a[j\vN

    OOO

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    47/52

    3%E@;(*, M.. S5) *)' .@(?;.%

    T!e sorting algorit!% 'ergesort produces a sorted se*uence by sorting its to !alves and%erging t!e% 4it! a ti%e co%plexity o$ ;1n log1n22 'ergesort is opti%al

    Si%ilar to 0uicksort, t!e 'ergesort algorit!% is based on a divide and con*uer strategyFirst, t!e se*uence to be sorted is deco%posed into to !alves 1ivide2 Eac! !al$ issorted independently 1Con*uer2 T!en t!e to sorted !alves are %erged to a sortedse*uence 1Co%bine2

    T!e $olloing procedure %ergesort sorts a se*uence a $ro% index lo to index !i

    T!e correctness o$ t!e algorit!% $ollos $ro% t!e $act t!at in t!e last step 1it! ! 32 an ordinaryInsertion Sort is per$or%ed on t!e !ole array ut since data are presorted by t!e preceding steps 1! 7, :, 83, 2 only $e Insertion Sort steps are su$$icient &o %any exactly ill be t!e subject o$ t!e$olloing analysis T!e above se*uence o$ !Rs1denoted as !-se*uence in t!e $olloing2 is just one o$ several possibleN actually, t!e per$or%ance o$S!ellsort depends on !ic! !-se*uence is used

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    48/52

    void %ergesort1int lo, int !i2

    M

    i$ 1loX!i2

    M

    int %1lo+!i2G8N

    %ergesort1lo, %2N

    %ergesort1%+3, !i2N

    %erge1lo, %, !i2NO

    First, index % in t!e %iddle beteen lo and !i is deter%ined T!en t!e $irst part o$ t!e se*uence 1$ro% loto %2 and t!e second part 1$ro% %+3 to !i2 are sorted by recursive calls o$ %ergesort T!en t!e tosorted !alves are %erged by procedure %erge Becursion ends !en lo !i, ie !en a subse*uenceconsists o$ only one ele%ent

    T!e %ain ork o$ t!e 'ergesort algorit!% is per$or%ed by $unction %erge T!ere aredi$$erent possibilities to i%ple%ent t!is $unction

    Function %erge is usually i%ple%ented in t!e $olloing ayK T!e to !alves are $irst copied into anauxiliary array b T!en t!e to !alves are scanned by pointers i and j and t!e respective next-greatestele%ent at eac! ti%e is copied back to array a 1Figure 82

    (t t!e end a situation occurs !ere one index !as reac!ed t!e end o$ its !al$, !ile t!e ot!er !as notT!en, in principle, t!e rest o$ t!e ele%ents o$ t!e corresponding !al$ !ave to be copied back (ctually,t!is is not necessary $or t!e second !al$, since 1copies o$2 t!e re%aining ele%ents are already at t!eirproper places

    void %erge1int lo, int %, int !i

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    49/52

    M

    int i, j, kN

    i9N jloN

    GG copy $irst !al$ o$ array a to auxiliary array b!ile 1jX%2

    b[i++\a[j++\N

    i9N kloNGG copy back next-greatest ele%ent at eac! ti%e

    !ile 1kXj @@ jX!i2

    i$ 1b[i\Xa[j\2

    a[k++\b[i++\N

    else

    a[k++\a[j++\N

    GG copy back re%aining ele%ents o$ $irst !al$ 1i$ any2

    !ile 1kXj2

    a[k++\b[i++\N

    O

    4%E@;(*, A5*)'? D.*, T.6',*:.%

    Introduction to (lgorit!% esign Tec!ni*ues

    G.. A5*)'?#

    (n opti%iation proble% is one in !ic! you ant to $ind, not just a solution, butt!e best solution

    f( 5greedy algorit!%6 so%eti%es orks ell $or opti%iation proble%sf( greedy algorit!% orks in p!ases (t eac! p!aseKfVou take t!e best you can get rig!t no, it!out regard $or $uture

    conse*uencesfVou !ope t!at by c!oosing a local opti%u% at eac! step, you ill end up

    at a global opti%u%

    Exa%pleK Counting %oney

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    50/52

    fSuppose you ant to count out a certain a%ount o$ %oney, using t!e $eestpossible bills and coinsf( greedy algorit!% ould do t!is ould beK

    (t eac! step, take t!e largest possible bill or coin t!at does not overs!oot fExa%pleK To %ake =7_, you can c!ooseK fa A bill f

    a 3 bill, to %ake =

    fa 8Ah coin, to %ake =8A f( 39h coin, to %ake =7A f$our 3h coins, to %ake =7_fFor

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    51/52

    original setT!e ti%e co%plexity o$ t!e algorit!% satis$ies t!e recurrence e*uation

    !ose solution is T1n2 ;1n log n2

    yna%ic "rogra%%ing (lgorit!%sT!e approac! assu%es a recursive solution $or t!e given proble%, it! a botto%-up evaluation o$ t!esolution T!e subsolutions are recorded 1in tables2 $or reuse

    %*). :*6 5) (5*)'? (, .@;(*,%

    0uick sort

    0uicksort is a $ast sorting algorit!%, !ic! is used not only $or educational purposes, but idelyapplied in practice ;n t!e average, it !as ;1n log n2 co%plexity, %aking *uicksort suitable $or sortingbig data volu%es

    T!e divide-and-con*uer strategy is used in *uicksort elo t!e recursion step isdescribedK3 C!oose a pivot value 4e take t!e value o$ t!e %iddle ele%ent as pivot value, but it can be any value, !ic! is in range o$ sorted values, even i$ it doesnRt present in t!e array8 "artition Bearrange ele%ents in suc! a ay, t!at all ele%ents !ic! are lesser t!an t!e pivot go to t!e le$t part o$ t!e array and all ele%ents greater t!an t!e pivot, go to t!e rig!t part o$ t!e array #alues e*ual to t!e pivot can stay in any part o$ t!e array /otice, t!at array %ay be divided in non-e*ual parts7 Sort bot! parts (pply *uicksort algorit!% recursively to t!e le$t and t!e rig!t partsT!ere are to indices i and j and at t!e very beginning o$ t!e partition algorit!% i points to t!e $irstele%ent in t!e array and j points to t!e last one T!en algorit!% %oves I $orard, until an ele%ent it!value greater or e*ual to t!e pivot is $ound Index j is %oved backard, until an ele%ent it! valuelesser or e*ual to t!e pivot is $ound I$ i j t!en t!ey are sapped and i steps to t!e next position 1i + 32,j steps to t!e previous one 1j- 32 (lgorit!% stops, !en i beco%es greater t!an j ($ter partition, all values be$ore i-t! ele%ent areless or e*ual t!an t!e pivot and all values a$ter j-t! ele%ent are greater or e*ual to t!e pivot;n t!e average *uicksort !as ;1n log n2 co%plexity, but strong proo$ o$ t!is $act is not trivial and notpresented !ere Still, you can $ind t!e proo$ in [3\ In orst case, *uicksort runs ;1n82 ti%e, but on t!e%ost ZpracticalZ data it orks just $ine and outper$or%s ot!er ;1n log n2 sorting algorit!%svoid *uickSort1int arr[\, int le$t, int rig!t2 Mint i le$t, j rig!tNint t%pNintpivot arr[1le$t + rig!t2 G 8\NG partition G!ile 1i X j2 M!ile 1arr[i\ X pivot2i++N!ile 1arr[j\ L pivot2j--Ni$ 1i X j2 M

  • 8/13/2019 17484 Answe Key GATE 2014 instrumentation engineering

    52/52

    t%p arr[i\N

    arr[i\ arr[j\N

    arr[j\ t%pNi++N

    j--NOONG recursion Gi$ 1le$t X j2*uickSort1arr, le$t, j2Ni$ 1i X rig!t2*uickSort1arr, i, rig!t2NO