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

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Dernier (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View 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