SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Plus 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
 

Plus 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 ...
 

Dernier

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
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
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
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
 

Dernier (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
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
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
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
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
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
 

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