import heapq
from datetime import datetime
def sort_dates_limited_memory(records):
"""
Sorts a list of date records using a min-heap for limited memory.
Args:
records: A list of records, where each record contains a date value.
Assumes each record has a 'date' attribute that is a datetime object.
Returns:
A list of records sorted by date in ascending order.
"""
if not records:
return []
heap = [] # Min-heap to store records
result = []
# Initialize the heap with the first record
heapq.heappush(heap, (records[0].date, records[0]))
for i in range(1, len(records)):
# Compare the current record's date with the smallest date in the heap
date, record = heapq.heappop(heap)
if records[i].date > date:
# Current record is later than the smallest date in the heap
heapq.heappush(heap, (records[i].date, records[i]))
else:
# Current record is earlier than or equal to the smallest date in the heap
heapq.heappush(heap, (date, record))
heapq.heappush(heap, (records[i].date, records[i]))
# Extract records from the heap in sorted order
while heap:
date, record = heapq.heappop(heap)
result.append(record)
return result
Add your comment