Sub topic 5
Sorted files: binary search and costly updates
This chapter assumes you know binary search, ceiling and floor arithmetic, and the blocking factor from the earlier chapters. It also assumes you know that a disk is read one block at a time, so the cost of an operation is counted in block accesses.
What a sorted file is
A sorted file, also called an ordered or sequential file, stores its records physically in order of one field, the ordering field. When the ordering field is also a key (no two records share a value), it is the ordering key field. Block 1 holds the smallest values, block 2 the next smallest, and so on.
Sorting buys one thing: because the order is known, you can jump to the middle of the file and decide which half to discard. A heap file cannot do this.
The notation from earlier chapters carries over:
- r is the number of records and R is the record size.
- bfr = floor(B / R) is the number of records per block.
- b = ceil(r / bfr) is the number of data blocks.
Searching on the ordering field
Binary search treats the file as an array of b blocks. Read the middle block, compare the search key with the first and last keys in that block, and keep the half that can contain the key. Searching inside a block is free, because the block is already in memory and only disk reads count.
The cost is about ceil(log2 b) block accesses.
Take B = 1024 bytes, R = 100 bytes, and r = 30,000 records.
- bfr = floor(1024 / 100) = 10 records per block.
- b = ceil(30000 / 10) = 3000 blocks.
- A heap file needs b / 2 = 1500 accesses on average for a key that exists, and 3000 in the worst case.
- A sorted file needs ceil(log2 3000) = 12 accesses, because 2^11 = 2048 < 3000 <= 4096 = 2^12.
The following program reproduces these numbers. It also shows the cost with a sparse primary index, which later chapters cover.
import math
def block_costs(B, R, r, V, P):
# B: block size, R: record size, r: number of records
# V: key (search field) size, P: block pointer size
bfr = B // R # records per block (unspanned)
b = math.ceil(r / bfr) # blocks in the data file
bfi = B // (V + P) # index entries per block
bi = math.ceil(b / bfi) # blocks in a sparse primary index
return {
"bfr": bfr,
"data_blocks": b,
"heap_avg_search": b / 2,
"sorted_binary_search": math.ceil(math.log2(b)),
"primary_index_search": math.ceil(math.log2(bi)) + 1,
}
print(block_costs(B=1024, R=100, r=30000, V=9, P=6))It prints a blocking factor of 10, 3000 data blocks, 1500.0 for the heap average, 12 for the sorted file, and 7 with the sparse index. The sorted file is more than 100 times cheaper than the heap file for this lookup.
Searching on other fields
The ordering helps only for the ordering field. A query on any other field, such as WHERE salary = 40000 when the file is sorted by emp_id, has no usable order. It costs the same as in a heap file: b / 2 on average when the value exists, and b when it does not.
Ordering also helps in two other ways:
- Range queries. For
emp_id BETWEEN 1000 AND 1500, binary search finds the first matching block. You then read consecutive blocks until the keys pass the upper bound. The cost is ceil(log2 b) plus the number of blocks that hold matching records, minus one because the first block is already counted. - Ordered output. Reading the file in sorted order needs no sort step. A heap file would need an external sort.
Why updates are costly
Records must stay in order. The file has no gaps, so changing it can force many records to move.
Insertion. The new record belongs at a specific position found by binary search. Every record after that position shifts forward to open a slot, and the last record may spill into a new block. On average you shift half the file, so you read b / 2 blocks and write b / 2 blocks. The total is about b + ceil(log2 b) accesses.
With b = 3000 that is roughly 3012 accesses. A heap file does the same insertion in 2 accesses: read the last block, append the record, and write the block back. In the worst case, a new smallest key, the whole file shifts: about 2b accesses.
Deletion. Deleting a record leaves a hole. You can close it by shifting later records back, which has the same cost as insertion. Most systems instead set a deletion marker on the record and leave the hole in place. Periodic reorganisation then removes the marked records and rewrites the file.
Modification. The cost depends on which field changes:
- A non-key, non-ordering field changes in place. Find the record by binary search, then write the block back: ceil(log2 b) + 1 accesses.
- A change to the ordering field moves the record to a different position. It costs a deletion plus an insertion.
Even when the target block has a free slot, the cost is small only if the file was left with spare space. A file packed full with no slack always takes the expensive path.
Reducing the update cost
Two common techniques avoid shifting records on every insertion:
- Overflow (transaction) file. New records go to an unsorted overflow file, which costs 2 accesses per insertion as in a heap file. From time to time the system sorts the overflow file and merges it with the main file in one pass. The cost is that a search must check the main file with binary search and then scan the overflow file linearly.
- Spare space in each block. Leave each block partly empty at load time. An insertion then shifts records only inside one block. This idea returns in B-trees, which keep nodes between half full and full.
Heap versus sorted file
| Operation | Heap file | Sorted file (ordering field) |
|---|---|---|
| Search by ordering key | b / 2 average, b worst | ceil(log2 b) |
| Search by other field | b / 2 average, b worst | b / 2 average, b worst |
| Range query | b (full scan) | ceil(log2 b) + matching blocks |
| Insert | 2 | about b + ceil(log2 b) |
| Delete | search, then mark | search, then mark or shift |
| Read in sorted order | needs external sort | scan the file |
Edge cases and GATE conventions
- Unspanned records. The formula b = ceil(r / floor(B / R)) assumes no record crosses a block boundary. If records may span blocks, use b = ceil(r * R / B). Check which one the question states.
- Search miss. Binary search takes the same ceil(log2 b) accesses whether or not the key exists. A heap search costs b on a miss, but only b / 2 on average on a hit.
- Floor versus ceiling. Some books give the worst case as floor(log2 b) + 1. For b = 3000 this is also 12. The two forms differ only when b is a power of two, so use the form the question's source uses.
- Duplicates. If the ordering field is not a key, binary search finds one matching record. Equal records sit next to each other, so you then read the neighbouring blocks to collect them all.
Binary search still needs about log2 b block reads, and every probe is a random disk access. The next chapters add an index so that only a few blocks are read.
Exercise
A file has 40,000 fixed-length records of 200 bytes each, stored unspanned in 4096-byte blocks and sorted on a key field. (a) How many blocks does the file occupy? (b) How many block accesses does a binary search for an existing key need? (c) Roughly how many block accesses does an average insertion need, ignoring any free space in blocks?
Show answer
(a) bfr = floor(4096 / 200) = 20 records per block, so b = ceil(40000 / 20) = 2000 blocks. (b) ceil(log2 2000) = 11, because 2^10 = 1024 < 2000 <= 2048 = 2^11. (c) The insertion shifts about half the file, so it reads about 1000 blocks and writes about 1000. With the search that is about 2000 + 11, roughly 2011 accesses.
Exercise
The file in the previous exercise is sorted on emp_id. How many block accesses does the query "find the record with phone = 98765" need on average if the phone number exists, and why does the sorting not help?
Show answer
The file is not ordered by phone, so the only option is a linear scan. On average it reads half the blocks, 2000 / 2 = 1000 block accesses. The worst case, or a phone number that does not exist, needs all 2000 blocks.