Write a k-way merge algorithm for K sorted files too large to fit in RAM. Use a min-heap to efficiently select the smallest element from K active file buffers. Implement buffered I/O to read and write in 64KB chunks.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import heapq
CHUNK_SIZE = 64 * 1024 # 64KB
class BufferedLineReader:
def __init__(self, filepath):
self.f = open(filepath, 'r', buffering=CHUNK_SIZE)
self.buffer = ''
self.lines = []
def next_line(self):
while not self.lines:
chunk = self.f.read(CHUNK_SIZE)
if not chunk:
# No more data
if self.buffer:
line = self.buffer
self.buffer = ''
return line
else:
return None
data = self.buffer + chunk
parts = data.split('\n')
self.buffer = parts[-1] # Incomplete line stays in buffer
self.lines.extend(parts[:-1])
return self.lines.pop(0)
def close(self):
self.f.close()
class BufferedLineWriter:
def __init__(self, filepath):
self.f = open(filepath, 'w', buffering=CHUNK_SIZE)
self.buffer = []
def write_line(self, line):
self.buffer.append(line)
# Flush when buffer size exceeds CHUNK_SIZE roughly
if sum(len(l) + 1 for l in self.buffer) >= CHUNK_SIZE:
self.flush()
def flush(self):
if self.buffer:
self.f.write('\n'.join(self.buffer) + '\n')
self.buffer = []
def close(self):
self.flush()
self.f.close()
def k_way_merge(input_files, output_file):
readers = [BufferedLineReader(f) for f in input_files]
heap = []
# Initialize heap with first line of each file
for i, reader in enumerate(readers):
line = reader.next_line()
if line is not None:
heapq.heappush(heap, (line, i))
writer = BufferedLineWriter(output_file)
while heap:
smallest, idx = heapq.heappop(heap)
writer.write_line(smallest)
next_line = readers[idx].next_line()
if next_line is not None:
heapq.heappush(heap, (next_line, idx))
writer.close()
for r in readers:
r.close()
This code merges K sorted input files (assumed sorted by lines) into one output file, using a min-heap to efficiently select the smallest line at each step, and reads/writes buffered in 64KB chunks to handle files too large for RAM.
Here's one way to implement an external k‑way merge using a min–heap and explicit 64 KB buffering for input and output. This example assumes each input file contains sorted newline‑terminated records and merges them into a single sorted output:
python
import heapq
from typing import List, Optional
CHUNK_SIZE = 64 * 1024 # 64 KB
class BufferedLineReader:
def __init__(self, path: str):
# use a 64 KB underlying buffer on the OS side as well
self.f = open(path, 'r', buffering=CHUNK_SIZE)
self._buf = '' # leftover partial line from last chunk
self._lines = [] # lines not yet consumed
self._eof = False
def next_line(self) -> Optional[str]:
# Return the next line without the trailing '\n', or None if EOF
while not self._lines and not self._eof:
chunk = self.f.read(CHUNK_SIZE)
if chunk == '':
self._eof = True
# return any leftover partial line at EOF
if self._buf:
line, self._buf = self._buf, ''
return line
else:
return None
data = self._buf + chunk
parts = data.split('\n')
# all complete lines are in parts[0:-1]; last element may be partial
self._buf = parts[-1]
self._lines.extend(parts[:-1])
if self._lines:
return self._lines.pop(0)
return None
def close(self):
self.f.close()
class BufferedLineWriter:
def __init__(self, path: str):
self.f = open(path, 'w', buffering=CHUNK_SIZE)
self._buf = []
def write_line(self, line: str):
self._buf.append(line + '\n')
# flush when buffer exceeds 64 KB
if sum(len(s) for s in self._buf) >= CHUNK_SIZE:
self.flush()
def flush(self):
if self._buf:
self.f.write(''.join(self._buf))
self._buf = []
def close(self):
self.flush()
self.f.close()
def k_way_merge(input_paths: List[str], output_path: str):
readers = [BufferedLineReader(p) for p in input_paths]
writer = BufferedLineWriter(output_path)
heap = []
# initialize heap with first line from each reader
for idx, rdr in enumerate(readers):
line = rdr.next_line()
if line is not None:
heapq.heappush(heap, (line, idx))
# main merge loop
while heap:
smallest, idx = heapq.heappop(heap)
writer.write_line(smallest)
next_line = readers[idx].next_line()
if next_line is not None:
heapq.heappush(heap, (next_line, idx))
# clean up
writer.close()
for rdr in readers:
rdr.close()
# Example usage:
# k_way_merge(['sorted1.txt', 'sorted2.txt', 'sorted3.txt'], 'merged_output.txt')
The BufferedLineReader reads from each file in 64 KB chunks, splitting them into lines while handling partial lines at chunk boundaries. The BufferedLineWriter accumulates output lines and flushes them to disk whenever the buffered data reaches roughly 64 KB. The merge function maintains a min‑heap keyed by the current line from each active reader to efficiently select the smallest available record at each step.