SlideShare uma empresa Scribd logo
1 de 19
Array implementationof a balanced binary search tree
Given a set oforderedelements, weaskourselvesifitispossibletobuild a binarysearchtreeupontheseelements in a sequential data structurelikeanarray; the answer, ofcourse, is yes. And in a bottom-up way. Theserepresentationdoesnotmakeuseofpointers, typical in a linkedrepresentationof a binarysearchtree, thereforeyousaveO(2n) memorylocations. Our BST willsave the orderedelementsonly at leafnodes, and internalnodeswillbevalorizedwithkey-valuesthatwill guide everysearchoperation. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Given the set containing5 elements, the balancedbinarysearchtreeoftheseelementsusuallyisrepresented in a ‘linked’ way likethis: 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
3 lvl 0 Treeismadeof 3 levels (withroot at level 0) Ithas5 ‘leaves’ and 4 ‘nodes’ Formally, ifnis the numberof elements, wewillhavenleaves     and n-1 internalnodes Itis a complete and balancedtree The numberofleavesisbetween2i e 2i+1, wherei and i+1 are the levelswhere the leaves are stored In this case wehave22< 5 < 23, 4 < 5 < 8 2 4 lvl 1 1 lvl 2 3 4 5 1 2 Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 lvl 3
Torepresentthattreeweuse the samerepresentationusedfor a similar data structure, usuallycalledheap(maxo min) A node at position i on anarray, willhavehisleftchild at position 2*i and his right child at position 2*i +1, and everychildnode in the arraywillhavehisownfather at position floor(i/2) Ourbinarytree on arraywillhave(n-1)+n+1 memorylocations,  (internalnodes)+ leaves+1 Final+1isabout the optiontoleaveempty    the first location of the array 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Ifwealreadyhave a linkedrepresentationof the treebased on oursortedelements, itis possibile to transfer it in a arrayrepresentationsimplytraversing the levelsof the tree, keeping in mind previousformulasaboutchild and fatherspositions. Likethis the roothas position 1 and hischildren and      are stored at2*1=2 and  2*1+1=3 . Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2 3 3 4 2 2 4 1 3 4 5 1 2
Buthow do webuildthistree in a bottom-up way ifwe don’t have the linkedrepresentationof the tree, butonlyourelementssorted(usualli in a ascendingorder) ? Wedefinitelymust produce the sameresultof a treetraversingbylevels, seenbefore, so weneed the same number of memory locations like the array resulting the ‘transformation’ It is quite simple but we must note that our input array, with our elements, is in the final array but in a ‘strange’ way. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Note the elements(1 2 3 4 5) order: The leaves(redones), aresstored in a ascendingorderbut, let’s say, in a ‘broken’ sequence,    3 4 5 1 2 insteadof 1 2 3 4 5 Thisis the directconsequenceof the treelevels Wemustfind out whatelementsfromour input arraywemustmove in anotherpositions Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
Weuse the basictheoryofbinarytrees and it’s link with the powerof the number 2 anwewilluse the toollog2(log base 2) Wesaidthatleaves are storedbetween the level 2i and 2i+1”,, they are practically spread at most in twodifferentand sequentiallevels, i and i+1 Wehavetofind out whatvaluesofourelementmusto go at level i and the otherseventuallywill go on the next level, i+1 Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
In ourexamplewehavethat 22< 5 < 23 ,  4 < 5 < 8 In thisimagewe note thatonly ONE nodeoflevel i ( in this case i=2) is a internalnodeoflevel i ( the other are onlyleaves in red) and thisnodebringstwoleaves in the level i+1 Wehavetofindthesnodes, thatbringscertainelementstobe on level i+1: ifwesubtract 4 from 5, weobrain the numberofnodethatwe are lookingfor, in this case 1 nodethatbrings 2 elementstobeleaves in level i+1 Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
This 2  ( is the resultof 1*2, [numer_of_node_we_were_looking_for]*2 ),  represent the numberofelementtomovefrom head to the tailofour input vector Doingthisweobtain the right orderwewerelookingfor, like in the level-traversalrepresentationshownbefore. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
Firtswemustunderstandhowtoobtainthat4 ofourexamplewithoutanyknowledgeabout the numberoflevelthere are in our future tree It’s timetouse some mathematics : log2   WE onlyknow the numberofelementsthatwillbeourleaves, in the example are 5 (formallyn) Using log andfloor()  wefound the valuethatwe are lookingforof the level i. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
log2 5 = 2.3219... floor(log2 5) = 2 Nowwehave the numberofleveli  Toknowhowmanynodes are usuallystored at level i in a full tree, eweusepowersof 2 nodeNumber=2floor(log2 n)  = 2floor(log2 5)  = 22 = 4 And therewehaveour 4! Therefore ,5 – 4 =1   and 1*2= 2; wemustmove 2 elementsfrom head totail Let’s now complete our BST Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Let’s create anarrayoflenght (internalnodes)+(leaves)+1, in our case 10 ( 4 + 5 +1) , and weourvectorwithmovedelements Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Foreveryfre location, from bottom to top, wemustchoose the key-valuetolead the search Ifcurrentnodehasn’t ‘nephews’ we take the valueofhisleftchild Otherwisewe look for the last ‘nephew’ on the right from the leftchild Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 Index 4, hasonlychildren take the leftvalue(2*i) Alsoforindex 3(at position 6 = 2*i, i=3).
Index 2, has ‘nephews’, we take the last right on of the leftchildofnode Alsofor position 1, root Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
Wehavefinallybuilt the balancedbinarysearchtree, savingtime and memorywith the useof 2 formulasforsearching Youmaywanttocheckifyou are already or you are goingtofind a value out ofbounds, topreventeruntimeerrors Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 3 2 4 1 3 4 5 1 2 1 3 4 5 1 2
Done. Nioi Pier Giuliano  Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2

Mais conteúdo relacionado

Semelhante a Balanced binary search tree on array

6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...trangiaphuc362003181
 
2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차Moonki Choi
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
CipherKey Algorithm
CipherKey AlgorithmCipherKey Algorithm
CipherKey Algorithmijtsrd
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Week09
Week09Week09
Week09hccit
 
Technical aptitude questions_e_book1
Technical aptitude questions_e_book1Technical aptitude questions_e_book1
Technical aptitude questions_e_book1Sateesh Allu
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure Eman magdy
 
Using Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigDataUsing Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigDataAnalyticsWeek
 

Semelhante a Balanced binary search tree on array (20)

6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
6-Sorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrti...
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차2021 여름방학 정기 세미나 1주차
2021 여름방학 정기 세미나 1주차
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Lecture10
Lecture10Lecture10
Lecture10
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
CipherKey Algorithm
CipherKey AlgorithmCipherKey Algorithm
CipherKey Algorithm
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 
Review session2
Review session2Review session2
Review session2
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
 
Week09
Week09Week09
Week09
 
CMT
CMTCMT
CMT
 
Technical aptitude questions_e_book1
Technical aptitude questions_e_book1Technical aptitude questions_e_book1
Technical aptitude questions_e_book1
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
 
Buacm 3
Buacm 3Buacm 3
Buacm 3
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
 
Using Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigDataUsing Topological Data Analysis on your BigData
Using Topological Data Analysis on your BigData
 

Mais de Pier Giuliano Nioi

Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...Pier Giuliano Nioi
 
Presentazione tesi multitouch
Presentazione tesi multitouch Presentazione tesi multitouch
Presentazione tesi multitouch Pier Giuliano Nioi
 
3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devices3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devicesPier Giuliano Nioi
 
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...Pier Giuliano Nioi
 

Mais de Pier Giuliano Nioi (6)

Presentazione
PresentazionePresentazione
Presentazione
 
Eple thesis
Eple thesisEple thesis
Eple thesis
 
Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...Implementazione hardware/software di un sistemamultitouch per l'interazione u...
Implementazione hardware/software di un sistemamultitouch per l'interazione u...
 
Presentazione tesi multitouch
Presentazione tesi multitouch Presentazione tesi multitouch
Presentazione tesi multitouch
 
3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devices3d Graffiti 3d tag : a concept of augmented reality form mobile devices
3d Graffiti 3d tag : a concept of augmented reality form mobile devices
 
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
Albero binario di ricerca bilanciato implementato su array - balanced bst on ...
 

Último

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 

Último (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 

Balanced binary search tree on array

  • 1. Array implementationof a balanced binary search tree
  • 2. Given a set oforderedelements, weaskourselvesifitispossibletobuild a binarysearchtreeupontheseelements in a sequential data structurelikeanarray; the answer, ofcourse, is yes. And in a bottom-up way. Theserepresentationdoesnotmakeuseofpointers, typical in a linkedrepresentationof a binarysearchtree, thereforeyousaveO(2n) memorylocations. Our BST willsave the orderedelementsonly at leafnodes, and internalnodeswillbevalorizedwithkey-valuesthatwill guide everysearchoperation. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 3. Given the set containing5 elements, the balancedbinarysearchtreeoftheseelementsusuallyisrepresented in a ‘linked’ way likethis: 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 4. 3 lvl 0 Treeismadeof 3 levels (withroot at level 0) Ithas5 ‘leaves’ and 4 ‘nodes’ Formally, ifnis the numberof elements, wewillhavenleaves and n-1 internalnodes Itis a complete and balancedtree The numberofleavesisbetween2i e 2i+1, wherei and i+1 are the levelswhere the leaves are stored In this case wehave22< 5 < 23, 4 < 5 < 8 2 4 lvl 1 1 lvl 2 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 lvl 3
  • 5. Torepresentthattreeweuse the samerepresentationusedfor a similar data structure, usuallycalledheap(maxo min) A node at position i on anarray, willhavehisleftchild at position 2*i and his right child at position 2*i +1, and everychildnode in the arraywillhavehisownfather at position floor(i/2) Ourbinarytree on arraywillhave(n-1)+n+1 memorylocations, (internalnodes)+ leaves+1 Final+1isabout the optiontoleaveempty the first location of the array 3 2 4 1 3 4 5 1 2 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 6. Ifwealreadyhave a linkedrepresentationof the treebased on oursortedelements, itis possibile to transfer it in a arrayrepresentationsimplytraversing the levelsof the tree, keeping in mind previousformulasaboutchild and fatherspositions. Likethis the roothas position 1 and hischildren and are stored at2*1=2 and 2*1+1=3 . Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2 3 3 4 2 2 4 1 3 4 5 1 2
  • 7. Buthow do webuildthistree in a bottom-up way ifwe don’t have the linkedrepresentationof the tree, butonlyourelementssorted(usualli in a ascendingorder) ? Wedefinitelymust produce the sameresultof a treetraversingbylevels, seenbefore, so weneed the same number of memory locations like the array resulting the ‘transformation’ It is quite simple but we must note that our input array, with our elements, is in the final array but in a ‘strange’ way. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 8. Note the elements(1 2 3 4 5) order: The leaves(redones), aresstored in a ascendingorderbut, let’s say, in a ‘broken’ sequence, 3 4 5 1 2 insteadof 1 2 3 4 5 Thisis the directconsequenceof the treelevels Wemustfind out whatelementsfromour input arraywemustmove in anotherpositions Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
  • 9. Weuse the basictheoryofbinarytrees and it’s link with the powerof the number 2 anwewilluse the toollog2(log base 2) Wesaidthatleaves are storedbetween the level 2i and 2i+1”,, they are practically spread at most in twodifferentand sequentiallevels, i and i+1 Wehavetofind out whatvaluesofourelementmusto go at level i and the otherseventuallywill go on the next level, i+1 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 10. In ourexamplewehavethat 22< 5 < 23 , 4 < 5 < 8 In thisimagewe note thatonly ONE nodeoflevel i ( in this case i=2) is a internalnodeoflevel i ( the other are onlyleaves in red) and thisnodebringstwoleaves in the level i+1 Wehavetofindthesnodes, thatbringscertainelementstobe on level i+1: ifwesubtract 4 from 5, weobrain the numberofnodethatwe are lookingfor, in this case 1 nodethatbrings 2 elementstobeleaves in level i+1 Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
  • 11. This 2 ( is the resultof 1*2, [numer_of_node_we_were_looking_for]*2 ), represent the numberofelementtomovefrom head to the tailofour input vector Doingthisweobtain the right orderwewerelookingfor, like in the level-traversalrepresentationshownbefore. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 1 3 4 5 1 2
  • 12. Firtswemustunderstandhowtoobtainthat4 ofourexamplewithoutanyknowledgeabout the numberoflevelthere are in our future tree It’s timetouse some mathematics : log2 WE onlyknow the numberofelementsthatwillbeourleaves, in the example are 5 (formallyn) Using log andfloor() wefound the valuethatwe are lookingforof the level i. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 13. log2 5 = 2.3219... floor(log2 5) = 2 Nowwehave the numberofleveli Toknowhowmanynodes are usuallystored at level i in a full tree, eweusepowersof 2 nodeNumber=2floor(log2 n) = 2floor(log2 5) = 22 = 4 And therewehaveour 4! Therefore ,5 – 4 =1 and 1*2= 2; wemustmove 2 elementsfrom head totail Let’s now complete our BST Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 14. Let’s create anarrayoflenght (internalnodes)+(leaves)+1, in our case 10 ( 4 + 5 +1) , and weourvectorwithmovedelements Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 15. Foreveryfre location, from bottom to top, wemustchoose the key-valuetolead the search Ifcurrentnodehasn’t ‘nephews’ we take the valueofhisleftchild Otherwisewe look for the last ‘nephew’ on the right from the leftchild Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 16. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 Index 4, hasonlychildren take the leftvalue(2*i) Alsoforindex 3(at position 6 = 2*i, i=3).
  • 17. Index 2, has ‘nephews’, we take the last right on of the leftchildofnode Alsofor position 1, root Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2
  • 18. Wehavefinallybuilt the balancedbinarysearchtree, savingtime and memorywith the useof 2 formulasforsearching Youmaywanttocheckifyou are already or you are goingtofind a value out ofbounds, topreventeruntimeerrors Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2 3 2 4 3 2 4 1 3 4 5 1 2 1 3 4 5 1 2
  • 19. Done. Nioi Pier Giuliano Università degli Studi di Cagliari Corso di Laurea in Tecnologie Informatiche Algoritmi e Strutture Dati 2