import heapq
def sort_log_streams(log_streams, max_memory):
"""
Sorts records of log streams for backward compatibility with limited memory usage.
Args:
log_streams (list of lists): A list of log streams, where each stream is a list of records.
max_memory (int): The maximum number of records that can be stored in memory at once.
Returns:
list: A sorted list of all records from all log streams.
"""
sorted_records = []
heap = [] # Use a min-heap to track the smallest elements
for stream in log_streams:
for record in stream:
if len(heap) < max_memory:
heapq.heappush(heap, record) # Add to heap if memory allows
else:
if record > heap[0]: # If current record is larger than the smallest in heap
heapq.heapreplace(heap, record) # Replace smallest with current record
# Extract sorted records from the heap
while heap:
sorted_records.append(heapq.heappop(heap))
return sorted_records[::-1] # Reverse to get ascending order
if __name__ == '__main__':
# Example usage
log_streams = [
[1, 5, 2, 8],
[3, 7, 4, 9],
[6, 10, 0, 11]
]
max_memory = 5
sorted_log = sort_log_streams(log_streams, max_memory)
print(sorted_log)
Add your comment