L11_data_structures

# L11_data_structures - Sorted Arrays As Lists Introduction...

This preview shows pages 1–3. Sign up to view the full content.

1 Introduction to Data Structures For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Sorted Arrays As Lists | Arrays are used to store a list of values | Arrays are contained in contiguous memory z Recall – inserting a new element in the middle of an array requires later elements to be "shifted". For large lists of values, this is inefficient. void insertSorted(int value, int &length, int list[]) { int i = length - 1; while (list[i] > value) { list[i + 1] = list[i]; i--; } list[i + 1] = value; length++; } Shifting array elements that come after the element being inserted 37 29 13 8 4 81 32 93 7 6 4 Insert 6 Sorted Arrays | Due to the need to "shift" elements, sorted arrays are: z Inefficient when inserting into the middle or front z Inefficient when deleting from the middle or front z Efficient for searching | Since inserting and deleting are common operations, we need to find a data structure which allows more efficiency z Contiguous memory will not work – will always require a shift z "Random" placement requires "random" memory locations z Dynamic allocation provides "random" locations, and means that the list can grow as much as necessary z The maximum size need not be known – ever This is not true for arrays, even dynamically allocated arrays Intro To Linked Lists | A linked list is a data structure which allows efficient insertion and deletion. | Consists of "nodes". Each node contains: z A value - the data being stored in the list z A pointer to another (the next) node | By carefully keeping pointers accurate, you can start at the first node, and follow pointers through entire list. | Graphically, linked list nodes are represented as follows: value ptr Linked List Info | Each node is dynamically allocated, so memory placement is "random" 1000 1004 1008 100C 1010 1014 1018 101C 1020 1024 1028 102C 1030 1034 1038 2 46 6 *0 2 *1030 *1010 4 *1004 "start" "start" The above linked list may be stored in memory as shown to the right. Deletion From Linked Lists Given the initial linked list: 2 4681 0 Delete node with value 4 2 0 Resulting in 681 0 2

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document