Arrays in memory#
An array stores elements of the same type in one continuous block of memory. The address of element i is start + i × size, so reading or writing a[i] is O(1) - instant, whatever the size.
index: 0 1 2 3 4
value: [ 12 ][ 45 ][ 7 ][ 89 ][ 23 ]
address: 1000 1004 1008 1012 1016 (4-byte ints)
| Operation | Array / vector |
|---|---|
read / write a[i] |
O(1) |
add at the end (push_back) |
O(1) on average |
| insert / delete in the middle | O(n) - elements must shift |
| search an unsorted array | O(n) |
| search a sorted array | O(log n) with binary search |
In C++ we usually use std::vector - a resizable array.
size = 6, first = 72, last = 64 72 100 95 58 88 64
Linear search - O(n)#
Check items one by one. Works on any array, sorted or not.
3 -1
Binary search - O(log n)#
On sorted data, look at the middle element. If the target is bigger, throw away the left half; if smaller, throw away the right half. Repeat.
Binary search वैसा ही है जैसे dictionary में शब्द ढूंढना - आप बीच का पन्ना खोलते हैं, देखते हैं शब्द आगे है या पीछे, और आधी किताब छोड़ देते हैं। हर कदम पर आधा हिस्सा हट जाता है, इसलिए 10 लाख शब्दों में भी लगभग 20 कदम में शब्द मिल जाता है। शर्त एक ही है - data sorted होना चाहिए।
step 1: low=0 high=9 mid=4 a[mid]=25 step 2: low=5 high=9 mid=7 a[mid]=58 found at index 7
Classic bugs: while (low < high) (misses the last element), low = mid instead of mid + 1 (infinite loop), and running binary search on unsorted data.
Binary search with the STL#
#include <algorithm>
bool present = binary_search(a.begin(), a.end(), 58); // true / false
auto it = lower_bound(a.begin(), a.end(), 50); // first element >= 50
int index = it - a.begin(); // 7 (value 58)
The two-pointer technique#
On a sorted array, two indices moving towards each other solve many problems in O(n) instead of O(n²) - pair sum, removing duplicates, reversing, merging.
6 5 4 3 2 1
Summary#
- Arrays: O(1) access by index, O(n) insert/delete in the middle.
- Linear search O(n) works anywhere; binary search O(log n) needs sorted data.
mid = low + (high - low) / 2; update withmid + 1/mid - 1.- STL:
binary_search,lower_bound,upper_bound. - Two pointers turn many O(n²) pair problems into O(n).