# Lecture 17: Preserve invariants to search and sort efficiently ## Preserve an invariant to obtain efficient operations **Instructor:** [Dr. Debasish Pattanayak](https://drdebmath.github.io)
## Binary search halves a sorted range without overflow ~~~cpp while (left <= right) { int middle = left + (right - left) / 2; if (values[middle] == target) return middle; if (values[middle] < target) left = middle + 1; else right = middle - 1; } ~~~ Each comparison discards one impossible half.
## A BST stores ordering in its left and right subtrees For every node: - keys in the left subtree are smaller; - keys in the right subtree are larger; - both subtrees obey the same invariant. Choose and document one policy for duplicate keys.
## BST insertion preserves order by following comparisons ~~~cpp struct Node { int key; Node* left; Node* right; }; Node* insert(Node* root, int key) { if (root == nullptr) return new Node{key, nullptr, nullptr}; if (key < root->key) root->left = insert(root->left, key); else if (key > root->key) root->right = insert(root->right, key); return root; } ~~~
## A heap keeps the highest-priority element at the root A max heap is a complete binary tree where every parent is at least its children. In a zero-based array, children of index
i
are `2*i+1` and `2*i+2`.
## heapify restores parent-child order after one local violation ~~~cpp void heapify(std::vector
& a, int size, int root) { int largest = root; int left = 2 * root + 1, right = left + 1; if (left < size && a[left] > a[largest]) largest = left; if (right < size && a[right] > a[largest]) largest = right; if (largest != root) { std::swap(a[root], a[largest]); heapify(a, size, largest); } } ~~~
## Merge sort recursively sorts halves and combines them stably 1. Divide the range into two halves. 2. Recursively sort each half. 3. Merge two sorted sequences into temporary storage. Merge sort is **stable**: records with equal keys keep their original relative order. It is O(n log n), and its array implementation uses additional storage. Heap sort is in-place but not stable.
## State the invariant before choosing a search or sort - Binary search exploits sorted-array order. - A BST encodes ordering in links. - A heap encodes priority in a complete tree. - heapify repairs a local invariant. - Merge sort applies recursive decomposition to sequences.