Search Sorted Array Binary Search Olog N Linked
Search • Sorted Array: Binary Search • O(log N) • Linked List: Linear Search • O(N) • Can we Apply the Binary Search algorithm on a linked list? • Why not?
Sorted Array • Rigid Structure – Fixed Size – Need to know the size of the largest data set – Wastage • Search: • Insertion: • Deletion: O (log n) O (n) - data movement
Binary Search Tree • • Binary Tree Dynamic Structure (size is flexible) Data is stored in a sorted fashion A special class of BST has the following properties: – Search: O (log n) – Insertion: O (log n) – Deletion: O (log n)
Binary Search Tree (BST) • A BST is a binary tree with the following properties: 1. Data value in the root node is greater than all the data values stored in the left subtree and is less than or equal to all the values stored in the right subtree. 2. Both the left subtree and right subtree are BSTs.
15 10 2 20 12 11 18 14 25 23 28
23 18 10 6 30 20 15 27 32 50
23 18 10 6 30 20 27 19 Violating the condition for BST 32 50
search(12) 15 10 2 20 12 11 18 14 t 25 23 28
search(23) 15 10 2 20 12 11 18 14 25 23 t 28
Binary Search Tree. Node * Binary. Tree: : search(int key) { Tree. Node *t = root; while (t != NULL) { if (t->data == key) break; else if (t->data > key) t = t->left; else t = t->right; } return t; }
search(13) 15 10 2 20 12 11 t 18 14 Æ 25 23 28
insert(19) insert(13) insert(4) 15 10 2 20 12 11 18 14 25 23 28
Binary Search Tree Search Parent void Binary. Tree: : search. Parent(int key, Tree. Node*& current, Tree. Node*& previous) { current = root; previous = NULL; while (current != NULL && current -> data != key) { previous = current; if (current->data > key) current = current->left; else current = current->right; } }
Binary Search Tree – Insert void Binary. Tree: : insert(int key) { Tree. Node *new. Tree. Node, *current, *previous; new. Tree. Node = new Tree. Node; new. Tree. Node ->left = NULL; new. Tree. Node ->right = NULL; new. Tree. Node->data = key; if (!root) root = new. Tree. Node; else { find. Parent(key, current, previous); if (current == NULL) { if (previous->data > key) previous->left = new. Tree. Node; else previous->right = new. Tree. Node; } else delete new. Tree. Node; } }
insert(13) 15 10 2 20 12 11 18 14 1Æ 3 Æ Æ 25 23 28
delete(12) delete(14) delete(2) 15 10 2 20 12 11 18 14 13 25 23 28
Delete a node from a BST 1. Locate the desired node by search; call it t 2. If t is a leaf, disconnect it from its parent and set the pointer in the parent node equal to NULL 3. If it has only one child then remove t from the tree by making t’s parent point to its child. 4. Otherwise, find the largest/smallest among t’s LST/RST; call it p. Copy p’s information into t. Delete p.
Time Complexity 15 10 2 20 12 11 18 14 Search Insert Delete 25 23 28
insert(15) insert(18) 15 18 insert(20) insert(26) insert(27) insert(34) 20 26 27 34 Time Complexity O(k) where k is the height
Height Balanced Trees k = log (n)
- Slides: 20