Sub topic 1
Disk storage and why block accesses are the cost measure
Prerequisites
This chapter assumes you know arrays, binary search, and balanced search trees. You should also be comfortable with logarithms and ceiling functions, and know that a database table holds records, each with a key field.
Disk blocks and the cost measure
A disk reads and writes data in fixed-size units called blocks, often 1024 or 4096 bytes. Reading one block takes far longer than comparing two keys in memory. Because of this, file algorithms count block accesses as their cost.
Records, blocking factor and number of blocks
Let the block size be B bytes, the record size R bytes, and the number of records r. The blocking factor bfr is the number of whole records that fit in one block:
bfr = floor(B / R)
The file then needs b = ceil(r / bfr) blocks.
import math
B, R, r = 1024, 100, 30000
bfr = B // R # 10 records per block
b = math.ceil(r / bfr) # 3000 blocks
print(bfr, b)File organisation: the options and what they trade off
| Organisation | Insertion | Equality search | Range search |
|---|---|---|---|
| Heap | Cheap | Linear, about b/2 blocks on average | Linear |
| Sorted | Costly, records shift | Binary, about log2(b) blocks | Efficient |
| Hashed | Cheap | About 1 block | Not supported |
Heap files: cheap insertion, linear search
A heap file places each new record in any block with free space, often the last block. Insertion is cheap. Search, however, scans blocks one by one. The average cost is b/2 block accesses, and the worst case is b.
Sorted files: binary search and costly updates
A sorted file keeps records ordered on the key. Binary search then needs ceil(log2 b) block accesses. Inserting or deleting a record may shift many records to keep the order, which is expensive.
Hashed files: equality lookups and their limits
A hash function maps a key to a bucket. An equality lookup usually reads about one block. Hashing cannot answer range queries, because nearby keys land in unrelated buckets.
Index basics: dense versus sparse
An index is a smaller file of (key, pointer) entries. A dense index has one entry for every record. A sparse index has one entry for each block, so it is smaller. A sparse index requires the data file to be sorted on the indexed key.
Exercise
A file has 30000 records of 100 bytes each, and the block size is 1024 bytes. How many blocks does a heap file need, and what is the average number of block accesses for an equality search?
Show answer
bfr = floor(1024 / 100) = 10, so b = ceil(30000 / 10) = 3000 blocks. The average search reads b / 2 = 1500 blocks.