235 Midterm 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

stack abstract data type

-a last in, first out data type - ex. a pez machine - functions: push, pop, empty, size, ect

Recursion

The process of a method calling itself in order to solve a problem. - must have a base and call to itself and head towards the base case ex. int factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1); } ex. double power(double x, int n) { if (n == 0) return 1; else if (n > 0) return x * power(x, n - 1); else return 1.0 / power(x, -n); }

c++ sets

The set and multiset are implementations of the Set ADT. The set is a template class that takes the following template parameters: template< class Key_Type, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > class set; ■where ■Key_Type: The type of the item contained in the set. ■Compare: A function class (functor) that determines the ordering of the keys. (Default is the less-than operator.) ■Allocator: The container uses an allocator object to dynamically handle its storage needs. (We will use the library supplied default.) ■Although not a requirement, C++ stores items in a set as ordered by their Compare function. If you iterate through a set, you get a sorted list of the contents

Pair

■The C++ standard library defines the class pair in the header <utility>. ■This class is a simple grouping of two values typically of different types. ■Since all of its members are public, it is declared as a struct. ex. template<typename T1, typename T2> struct pair { T1 first; T2 second; // Construct a pair from two values. pair(const T1& x, const T2& y) : first(x), second(y) {} // Construct a default pair. pair() : first(T1()), second(T2()) {} // Construct an assignable pair template<type Other_T1, type Other_T2> pair(const pair<Other_T1, Other_T2>& other) { first = other.first; second = other.second; } };

Hash tables

■The C++ standard library uses a special type of binary search tree, called a balanced binary search tree, to implement the ordered set and map classes. ■This provides access to items in O(log n) time. ■Sets and maps can also be implemented using a data structure known as a hash table, which has some advantages over balanced search trees. ■The goal of hash table is to be able to access an entry based on its key value, not its location. ■We want to be able to access an entry directly through its key value, rather than by having to determine its location first by searching for the key value in an array. ■The "order of elements" may change when the container is modified (upon insertion/deletion). ■Using a hash table enables us to retrieve an entry in constant time (on average, O(1)).

multiset

■The multiset is the same as the set except that it does not impose the requirement that the items be unique. ■The insert function always inserts a new item, and duplicate items are retained. ■However, the erase function removes all occurrences of the specified item because there may be duplicates. ■The functions lower_bound and upper_bound can be used to select the group of entries that match a desired value. ■If the item is present, both functions return iterators : ■lower_bound returns an iterator to the first occurrence of the specified value. ■upper_bound returns an iterator to the smallest item that is larger than the specified value. ■The desired entries are between the iterators returned by these two functions. ■If the item is not present, both upper_bound and lower_bound return an iterator to the smallest element that is larger than the specified entry.

stable sort

■There are also two functions named stable_sort, which are similar to the sort functions. ■The primary difference is that elements that are equal may not retain their relative ordering when sort is used, but they will retain their relative ordering when stable_sort is used. ■In other words, if there are two occurrences of an item, the one that is first in the unsorted array is guaranteed to be first in the sorted array only if stable_sort is used. ■This function call sorts an array in descending order: stable_sort(items, items + 16, greater<int>()); ■The sort function is slightly faster than stable_sort, so it should be used whenever the relative ordering of equal elements is unimportant.

Huffman tree

- A Huffman tree represents Huffman codes for characters that might appear in a text file - As opposed to ASCII or Unicode, Huffman code uses different numbers of bits to encode letters; more common characters use fewer bits - Many programs that compress files use Huffman codes

Tree Fullness and Completeness

- A full binary tree is a binary tree where all internal nodes have exactly 2 children - Note that the number of leaf nodes is one more than the number of internal nodes -complete: filled down to level h-1 - at level h, unfiled nodes are to the right predecessor: left right most node successor: right liftmost

namespace

- A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. - Organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. - The built in C++ library routines are kept in the standard namespace that includes stuff like cout, cin, string, vector, map, etc. - The using declaration introduces all members of another namespace into current namespace or block scope. - Because standard tools are used so commonly, it's popular to add "using namespace std" at the top of your source code so that you won't have to type the std:: prefix constantly.

Nested Class

- A nested (inner) class is a class which is declared inside an enclosing (outer) class. -if an inner class needs access to outer class members it must either: - you must pass an outer class reference (pointer) to the inner class via constructor param

Linked Lists

- All accesses to a singly-linked list are through the head Big O - Insertion beginning O(1) - Insertion middle O(n) - Insertion between 2 nodes that you know O(1) - Random access O(n) - Search O(n) - List a templated class like - vector is a double-linked list

Trees

- All previous data organizations we've studied are linear—each element can have only one predecessor and one successor - Accessing all elements in a linear sequence is O(n) - Trees are nonlinear and hierarchical - Tree nodes can have multiple successors (but only one predecessor) - Trees can represent hierarchical organizations of information: - class hierarchy - disk directory and subdirectories - family tree -binary tree: 2 children 1 parent - trees are recursive data structures - ¨Searching a binary search tree, generally is more efficient than linearly searching an ordered list—O(log n) versus O(n)

Assignment Operator

- Allows you to use = to assign an object to another t2=t1; calls the assignment operator since t2 exists

copy constructor

- Constructor used to make a copy of an existing class/struct instance Initialize object from another of the same type -Copy an object to pass it as an argument to a function -Copy an object to return it from a function -Called by: MyClass t1, t2; MyClass t3 = t1; since t3 is new

expression tree

- Each node contains an operator or an operand - Operands are stored in leaf nodes - Parentheses are not stored in the tree because the tree structure dictates the order of operand evaluation - Operators in nodes at higher tree levels are evaluated after operators in nodes at lower tree levels operands: external operators: internal

Stacks

- First In Last Out - if you push a palindrome on a stack and pop it back out, it will be the same since palindromes read the same backwards and forwards - Initialize template class stack<char> myStack; myStock.push(value); myStack.top(); myStack.pop(); youtube: infix to prefix using stack for extra credit

Swap function

- In order to save data, there is a swap function so you don't need to create a temporary object and do deep copies - swap switches addresses

Ordered List

- Insertion O(n) since you can't just push it on front - Create a has-a ordered list class from the list class, not is-a since we don't want to override all the functions - Delegation: Then we can use all the list functions that stay the same and use the list to store the data, then we can only write our own functions when needed ex. Insertion Circular list - Make last node point to the first and the first to the last in a doubly-linked list - Disadvantage: make sure to avoid infinite loop

Iterators

- Iterators bring you closer to container independence. - You're not making assumptions about random-access ability, storage format, efficiency of operations such as size(), or most algorithms. - You only need to know that the container has iterator capabilities. - Iterators enhance your code further with standard algorithms. - Depending on what it is you're trying to achieve, you may elect to use for_each(), find(), replace(), partition(), search(), transform(), sort(), ... - By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. - Your code is likely to be more efficient (given the right algorithm is chosen), correct, and reusable. - container iterator generally a nested class because it belongs to that class and ensures it is used correctly and has a parent

New vs Malloc

- New calls the malloc function, it is an operator not a function - On failure, new throws an error, malloc returns null

Overload postfix operator

- Overloading the postfix increment operator presents a challenge because the compiler must be able to distinguish between the signatures of the overloaded prefix and postfix increment operator functions. - The convention that has been adopted in C++ is that when the compiler sees the post-incrementing expression object++, it generates the member function call: myData.operator++(0) - The prototype for this operator function would be: Data operator++(int); - The argument 0 is strictly a "dummy value" that enables the compiler to distinguish between the prefix and postfix increment operator functions. - postfix returns a copy of the old value

Tree Traversal methods

- Preorder: visit root node, traverse TL , traverse TR - keep going left until you cant then go right and up - Inorder: traverse TL , visit root node, traverse TR (in order from least to greatest) - Postorder: traverse TL , traverse TR , visit root node (hit all children starting from left before hitting the parent)

C++ Memory Model

- The C++ memory model is an abstract machine for which the C++ programming language is defined. - Memory is one or more contiguous sequences of bytes. - A byte is a sequence of 8 or more bits and "bit" is a unit of storage large enough to hold one of two values. - Each byte is associated with a unique identifier known as its address. - Computer memory is classified as - Writable or non-writable. - Executable or non-executable. - Initialized or uninitialized. the following listed: high address - low address - environment variables - stack: (writable, non-executable) - available memory - dynamic data (heap): managed by programmer, (writable, non-executable) ex. new/delete - uninitialized static data, global variables: created by programmer, (readable, non-executable) - initialized data: Initialized when program starts (readable, non-executable) -program code - does not include virtual memory

Tree terminology

- The node at the top of a tree is called its root - The links from a node to its successors are called branches - The successors of a node are called its children - The predecessor of a node is called its parent - Each node in a tree has exactly one parent except for the root node, which has no parent - Nodes that have the same parent are siblings - A node that has no children is called a leaf node - Leaf nodes also are known as external nodes, and nonleaf nodes are known as internal nodes - A subtree of a node is a tree whose root is a child of that node - The level of a node is determined by its distance from the root - The height of a tree is the number of nodes in the longest path from the root node to a leaf node

Overload Prefix Operator

- The prefix and postfix versions of the unary increment and decrement operators can all be overloaded. - When the compiler sees the pre-increment expression on a Data data type: - Data myData; ++myData; - the compiler generates the member function call: myData.operator++() - The prototype for this operator function would be: Data& operator++(); -prefix returns a referennce

Compiling a C++ program

- The preprocessor merges include files with source files - preprocessor directive: a C program line beginning with # that provides an instruction to the preprocessor ex. #define ASPECT_RATIO 1.653 instead of const double AspectRatio = 1.653; 1. Compiler never sees ASPECT_RATIO - blind substitution. 2. Confusing if you get an error. 3. ASPECT_RATIO is not in the symbol table - problem for symbolic debugger. 4. AspectRatio may yield smaller code size. 5. For simple constants, prefer const objects or enums to #defines. - compiler turns source files into assembly - assembler turns assembly into object code - linker turns that into machine code

Vector class

- Vector push back is constant time amortized, with big O of amortized 1 -constant time since we only have to resize every n items so its big O amoritized 1 - Push back calls the reserve function and gets twice the space reserved

Shallow vs Deep Copy

- When you shallow copy an object, the copy is referring to the same object since the pointers are copied, not what the pointers are pointing to - Deep copy: copying an object so it doesn't affect the other, news up the data Copy constructor and assignment operator need to be overwritten to be deep

Deque

- a double-ended queue is an abstract data type that generalizes a queue where elements can be added or removed from the head or tail - differences from FIFO - restricted deques may only be able to push on to one side -store the deque contents in a circular buffer and resize when the buffer is full, resizing is amortized but can become expensive

Heap

- a heap is a complete binary tree - the root value is greater than or equal to any item in the tree (max heap) - you can only remove a root from a heap - min heap is a level order storage

Backtracking

- a problem-solving technique that involves keeping track of where in the solving process assumptions are made so that they may later be changed - Backtracking is an approach to implementing a systematic trial and error search for a solution with no repetition

Insertion Sort

- as you add cards, they are sorted - you go one card at a time and move it to its final position - Placing each item into the correct position in the list one at a time, like a hand of cards. Comparison/exchange: O(n) best O(N^2) worst

Constructors

- don't throw errors in a constructor! or else the object wont finish being constructed - keep them small

Searching a binary Tree recursively

- each probe eliminates half the tree - OlogN as long as the tree is about balanced ex. TL and TR have about the same number of nodes - worst case O(n) - its already sorted 1.if the tree is empty 2. Return null (target is not found)else if the target matches the root node's data 3. Return the data stored at the root nodeelse if the target is less than the root node's data 4. Return the result of searching the left subtree of the rootelse 5. Return the result of searching the right subtree of the root

Standard Library Containers

- many functions for containers already written and in standard library - some take function objects as params and do standard operations on containers -ex F for_each(II first, II last, Ffun) which applies fun function to each element in range

Backtracking

- returns the first solution ■Backtracking is an approach to implementing a systematic, non-repetitive, trial and error search for a solution to a maze. ■As one encounters a path junction, a path is chosen. ■Either you will reach your destination and exit the maze, or you won't be able to go any farther. ■If you can't go any farther, you will need to consider alternative paths—you will need to backtrack until you reach a fork and follow a branch you did not travel hoping to reach your destination. ■If you never try the same path more than once, you will eventually find a solution path if one exists. ■Problems that are solved by backtracking can be described as a set of choices made by some function. ■Recursion allows you to implement backtracking in a relatively straightforward manner. ■Each activation frame is used to remember the choice that was made at that particular decision point.algorithm.

Functor

-class that has overwritten the function operator - used because functions don't store state like classes do ex. class Inbetween{ private: int low; int high; public: InBetween(int l, int h); low(l); high(h); {} bool operator()(int x){return (low<x)&&(x<high);}

Queues

-first come, first serve -ADT Queue also called FIFO - Queue and stack methods all the same except for pop; -std::list as a queue container - queue is an adaptor class ex. queue push is list:push_back, queue front is list:front quiz code gorilla -make helper functions private -add comments -.cpp file

Merge Sort

-stable sort ■A merge is a common data processing operation performed on two sequences of data with the following characteristics: ■Both sequences are ordered by the same comparison operator (that is, both sequences are sorted). ■The result of the merge operation is a third sequence containing all the data from the first two sequences. ■Analysis of Merge Sort: ■For two input sequences each containing n elements, each element needs to move from its input sequence to the output sequence. ■Merge time is O(n). ■Space requirements: ■The array cannot be merged in place. ■Additional space usage is O(n). ■Each backward step requires a movement of n elements from smaller-size arrays to larger arrays; the effort is O(n). ■The number of steps which require merging is log n because each recursive call splits the array in half. ■The total effort to reconstruct the sorted array through merging is O(n log n).

Binary Search Tree

A data structure very similar to a tree with the following additional restrictions. Each node can have only 0, 1 or 2 leaf nodes. All left nodes and all of its descendants have smaller values that the root node, while all right nodes and all of its descendants have larger values than the root node. - everything on the left is less than everything on the right is greater than

Quicksort

All the elements in the left subarray are less than or equal to the pivot. All the elements in the right subarray are larger than the pivot. The pivot is placed between the two subarrays. The process is repeated until the array is sorted. -pivot in the right place after each pass

C++ Federation

C - Blocks, statements, preprocessor - Data types (weak), arrays, pointers Object-Oriented C++ - Classes (constructors, destructors) - Encapsulation, iheritance - Polymorphism, virtual functions (dynamic binding) Template Metaprogramming (TMP) - Generic programming part of C++ - "Compile-time execution" STL - Containers, iterators - Algorithms, function objects Built around templates and libraries

Selection Sort

For very large n we can ignore all but the significant term in the expression, so the number of •comparisons is O(n2) aka quadratic •exchanges is O(n) This comparison is performed (n - 1 - fill) times for each value of fill and can be represented by the following series:(n-1) + (n-2) + ... + 3 + 2 + 1 ■Selection sort is relatively easy to understand. ■The array is sorted by making several passes through the array, selecting a next smallest item in the array each pass and placing it immediately where it belongs in the array.

No parameter Constructor

If no constructors are defined in a class, the no-parameter constructor is provided by default

Linked List & Circular Array ADT Queue

Linked Lists - The time efficiency of using a single-linked or double-linked list to implement a queue is acceptable. - However, there are some inefficiencies: - Storage space is increased when using a linked list due to references stored in the nodes. - the more elements you and, the longer it takes to remove from the back O(n) - Pointer arithmetic. - A contiguous array Implementation mitigates space and pointer inefficiencies, but: - While insertion at rear of array is constant time O(1), removal from the front is linear time O(n). - While removal from rear of array is constant time O(1), insertion at the front is linear time O(n). Circular Array - A Circular Array ADT Queue uses an object with four size_t type data members: - size_t capacity; - size_t num_items; - size_t front_index; - size_t rear_index; - And a pointer to the data member, the_data to point to a dynamically-allocated array - amoritization over n items - Item Type* the_data; - And a default array allocation size - #define DEFAULT_CAPACITY 8 ■All three implementations of the Queue ADT are O(1). ■Although reallocating an array is an O(n) operation, it is amortized over n items, so the cost per item is O(1). ■Both linked-list implementations require more storage because extra space is required for links. ■C++ stores a copy of the data for a queue element in each node in addition to the links. ■a node in a single linked list stores a total of one pointer. ■a node in a double-linked list stores a total of two pointers. ■a node in a circular array stores just the data. ■A circular array that is filled to capacity requires half the storage of a single linked list to store the same number of elements (assuming that the data type requires the same amount of storage as a pointer). ■However, if the array were just reallocated, half the array would be empty, so it would require the same storage as a single-linked list.

switch statement

a C++ statement that can be used to code a multiple-alternative selection structure - allows multi-way branching. In many cases, using a switch statement can simplify a complex combination of if-else statements.

Blob

a collection of cells with a common value

abstract data type

a description of operations on a data type that could have multiple possible implementations. - ex you can't buy a vehicle but you can buy a car since vehicle is abstract

argc and argv

argument counter and argument values int main(int argc, char *argv[]) argc (as in argument counter): contains the number of arguments passed on to the program plus one; that means that a program run without any arguments will have the argc parameter value equal to 1 argv (as in argument values): an array of pointers to strings containing the arguments supplied to the program; they are stored in the following way: argv[0] contains the name of the running program argv[1] contains the string passed to the program as the first argument argv[n] contains the string passed to the program as the n-th argument

enum

quiz code wolf enum type { val_name, val_name, val_name } // type is one you created type name = val_name;

Iterator

quiz code: bear - an object that contains a node pointer - begin() points to first element, end() points to null after last element

const

quiz code: pigeon const member functions are bitwise const/bitwise const - if and only if it doesn't modify data members - easy to detect violations logical const - a member function that modifies what a pointer points to is bitwise const but not logical you could make an entire class const then change a few to mutable

Towers of Hanoi

recursion calls: 2^n n = number of disks // recursive function to solve tower of hanoi puzzle void move_disk(int disk, char from, char to, char temp) { if (disk == 1) { cout << "Move disk 1 from " << from << " to " << to << endl; } else { move_disk(disk - 1, from, temp, to); cout << "Move disk " << disk << " from " << from << " to " << to << endl; move_disk(disk - 1, temp, to, from); } }

Shell Sort: A Better Insertion Sort

■A Shell sort is a type of insertion sort, but with O(n3/2) or better performance than the O(n2) sorts. ■It is named after its discoverer, Donald Shell. ■A Shell sort can be thought of as a divide-and-conquer approach to insertion sort. ■Instead of sorting the entire array, Shell sort sorts many smaller subarrays using insertion sort before sorting the entire array. ■The initial subarrays will contain two or three elements, so the insertion sorts will go very quickly. ■After each collection of subarrays is sorted, a new collection of subarrays with approximately twice as many elements as before will be sorted. ■The last step is to perform an insertion sort on the entire array, which has been presorted by the earlier sorts.

maps

■A map is effectively a set of key-value pairs whose values are still accessed via the key (but not the key-value). - STL map keys are ordered (sorted) - iterators will return values in key sorted order. - STL unordered_map keys are not in any particular order with respect to either their keys. - The map is a template class that takes the following template parameters: - Key_Type: The type of the keys contained in the key set - Value_Type: The type of the values in the value set - Compare: A function class that determines the ordering of the keys; by default this is stl::less<K> - Allocator: The memory allocator for key objects; we will use the library-supplied default example: #include <iostream> #include <map> #include <string> using namespace std; int main() { map<string, string> myMap; myMap["Charlie Brown"] = "Manager"; myMap["Snoopy"] = "Catcher"; myMap["Lucy"] = "Right Field"; myMap["Linus"] = "2nd Base"; map<string, string>::iterator iter = myMap.begin(); while (iter != myMap.end()) { cout << iter->first << " => " << iter->second << endl; ++iter; } return 0;

Bubble sort

■Bubble sort (also known as sinking sort) is also a simple sorting algorithm ■The array is sorted by repeatedly stepping through the array, comparing adjacent pairs, and swapping them if they are in the wrong order, until the array is sorted. ■Smaller values bubble up to the top of the array and larger values sink immediately to the bottom with each pass. ■Selection sort and Bubble sort are quadratic sorts. ■The number of comparisons and exchanges is represented by (n - 1) + (n - 2) + ... + 3 + 2 + 1 ■Worst case: ■number of comparisons is O(n2). ■number of exchanges is O(n2). ■Compared to selection sort with its O(n2) comparisons and O(n) exchanges, bubble sort usually performs worse. ■If the array is sorted early, the later comparisons and exchanges are not performed and performance is improved. ■The best case occurs when the array is sorted already ■one pass is required (O(n) comparisons). ■no exchanges are required (O(1) exchanges). ■Bubble sort works well on arrays nearly sorted and worst on inverted arrays (elements are in reverse sorted order).

Chaining

■Chaining is an alternative to open addressing. ■Each table element references a linked list that contains all of the items that hash to the same table index. ■The linked list often is called a bucket. ■The approach sometimes is called bucket hashing. ■Chaining advantages: ■When looking for an item, only items with the same hash value are probed. ■The number of items is not limited by the hash table size. (No rehashing.) ■Items can be inserted at the end of the list (without further probes.) ■No need to replace a deleted item with a dummy item or mark. ■Open addressing advantages: ■Usually faster than chained hashing when the load factor is low because you don't have to follow pointers between list nodes. ■Chained hashing has the storage overhead of list pointers. ■If chains become long, then search time could become O(n). ■Reducing collisions effects hash table performance. ■The lower the load factor, the better the performance as there is a smaller chance of collision when a table is sparsely populated. ■Good hashing algorithms reduce the chance of collisions by evenly distributing probes throughout the hash table. If there are no collisions, search and retrieval performance is O(1) regardless of table size.

Generating Hash Codes

■For strings, simply summing the char values of all characters returns the same hash code for "sign" and "sing". ■One algorithm that has shown good results uses the following formula: s0 x 31(n-1) + s1 x 31(n-2) + ... + sn-1 where si is the ith character of the string of length n. ■"Cat" has a hash code of: 'C' x 312 + 'a' x 31 + 't' = 67,510 ■31 is a prime number, and prime numbers generate relatively few collisions.

c++ sort

■If people_list is a vector of Person objects, then: sort(people_list.begin(), people_list.end(), Compare_Person()); sorts the elements in people_list in ascending order based on their names. The Compare_Person function class is used to compare objects: struct Compare_Person { bool operator()(const Person& p1, const Person& p2) { return ((p1.family_name < p2.family_name) || ((p1.family_name == p2.family_name) && (p1.given_name < p2.given_name)); } }

template specialization

■It is possible in C++ to get a special behavior for a particular data type - this is called template specialization. ■Compilers that support partial specialization allow the programmer to specialize some (or all) of the template parameters while leaving others generic. ■When the compiler sees a class template instantiated in code, it will generally choose the most specialized template definition that matches the instantiation. ■An explicit specialization (one where all the template arguments are specified) will be preferred to a partial specialization if all the template arguments match.

Linear & Quadratic Probing

■Linear probing tends to form clusters of keys in the hash table, causing longer search chains. ■Quadratic probing can reduce the effect of clustering. ■Resolve collisions with a quadratic series (H+12, H+22, H+32, H+42}, ..., H+k2) ■For example, if an item has a hash code of 5, successive values of index will be 6 (5+1), 9 (5+4), 14 (5+9), 21 (5 +16), . . .

Heap Sort

■Merge sort time is O(n log n), but still requires, temporarily, n extra storage locations. ■Heapsort is also O(n log n), but does not require any additional storage. ■A max heap is used as its data structure with the largest value at the top. ■Once we have a heap, we can remove one item at a time from the heap and place it at the bottom of the heap. ■We then reheap by moving the larger of a node's two children up the heap if needed, so the new heap will have the next largest item as its root. ■As we continue to remove items from the heap, the heap size shrinks and the number of the removed items increases. ■After we have removed the last element, the array will be sorted. ■If we want to sort the sequence table bounded by the iterators first through last, we can consider the first item to be a heap of one item ■We now consider the general case where the items in the sequence from table[first] through table[first + n - 1] form a heap; ■Items from table[first + n] through table[last - 1] are not in the heap. ■As each item is inserted, we must "reheap" to restore the heap property. ■Because a heap of size n is a complete binary tree, it has log n levels ■Building a heap requires finding the correct location for an item in a heap with log n levels ■Each insert (or remove) is O(log n) ■With n items, building a heap is O(n log n) ■No extra storage is needed.

Quadratic Probing

■Quadratic probing can reduce the effect of clustering. ■Index, Index + 12, Index + 22, Index + 32, ... , Index + k2 ■An efficient way to calculate the next quadratic probe index is: k += 2; index = (index + k) % table.size(); ■For example, if the hash index is 5, quadratic probes would be: ■5, 6 ( 5 + 1), 9 (5 + 1 + 3), 14 (5 + 1 + 3 + 5), 21 (5 + 1 + 3 + 5 + 7), ... ■Other opening addressing problems: ■An item can't be inserted even when the table is not full. ■The program might get stuck in an infinite loop searching for an empty slot (table is full or quadratic hashing is cyclic.) ■If the table size is a prime number and it is never more than half full, this won't happen. However, requiring a half empty table wastes a lot of memory


Set pelajaran terkait

CLPS 0450 Final Exam Questions + Concepts

View Set

CompTIA Security+ Final Assessment (real)

View Set

college board questions + other things to know for bio

View Set

Psychology: Unit 4; Quiz 1: Learning; Quiz 2: Memory; Quiz 3: Thinking, Language, Consciousness, and Sleeping; Test

View Set

InterComm Ch. 1-4 - Quiz Questions

View Set

Acting Michael Caine (Chapter 1 & 2)

View Set