Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Analysis (COMP 410)

Similar presentations


Presentation on theme: "Data Structures and Analysis (COMP 410)"— Presentation transcript:

1 Data Structures and Analysis (COMP 410)
David Stotts Computer Science Department UNC Chapel Hill

2 Representing Trees as Arrays

3 Array Rep for any BT Not heap structure (complete binary tree)
4 18 11 9 3 7 16 21 12 Not heap structure (complete binary tree) just a random binary tree 7 21 4 18 3 11 12 16 9

4 Now get bigger… Add one node, double space needed in array
4 18 11 9 3 7 16 21 12 Add one node, double space needed in array 5 7 21 4 18 3 11 12 16 9 5

5 4 18 11 9 3 7 16 21 12 5 And bigger… 7 21 4 18 3 11 12 16 9 5 8 8

6 Array space used Some languages (without objects) would use huge space
Array element is a static collection of data, each element might need 1000’s bytes array[10000] of struct { int, real, char[48] }

7 array int real chars int real chars 1 . . .

8 Array space used In Java (and languages with objects, pointers) can improve this Array element is an object, then each space in the array is a 8-byte address Each object is a collection of data, might be large, but we only need a object for each occupied array location class Element { int, real, char[48] } array[10000] of Element array[0] = new Element { 3, 4.5, “now is the time”} array[4] = new Element { 1, 6.3, “for all good code”}

9 . . . 3 4.5 “now is the time” 2 6.3 “for all good code” array 1 2 3 4
3 4.5 “now is the time” 1 2 3 4 5 6 7 2 6.3 “for all good code” . . .

10 Static layout, big space for each array element, used or not dynamic layout, each array element 64-bits, then big space for only elements used

11 Other problems… Add a node 8 3 and 16 have now changed levels
When we add/move new nodes in a tree in the middle layers, we force rearrangement of values stored in the array Ex: 4 18 11 9 3 7 16 21 12 8 4 18 11 9 3 7 16 21 12 Add a node 8 between the 21 and 3 3 and 16 have now changed levels

12 Inner insert encoding the original tree
4 18 11 9 3 7 16 21 12 encoding the original tree 7 21 4 18 3 11 12 16 9

13 Inner insert Add a node 8 between the 21 and 3
4 18 11 9 3 7 16 21 12 8 Add a node 8 between the 21 and 3 7 21 4 18 11 12 9 3 16 8

14 Summary Array representation can be fast if the tree is built and then not changed (much) Changes in a tree require a lot of array element movement Array rep can be space inefficient if tree is not fairly full Array rep can be very space inefficient if array elements are static memory blocks rather than dynamically allocated objects

15 Beyond this is just templates
END Beyond this is just templates


Download ppt "Data Structures and Analysis (COMP 410)"

Similar presentations


Ads by Google