1. import heapq
  2. from datetime import datetime
  3. def sort_dates_limited_memory(records):
  4. """
  5. Sorts a list of date records using a min-heap for limited memory.
  6. Args:
  7. records: A list of records, where each record contains a date value.
  8. Assumes each record has a 'date' attribute that is a datetime object.
  9. Returns:
  10. A list of records sorted by date in ascending order.
  11. """
  12. if not records:
  13. return []
  14. heap = [] # Min-heap to store records
  15. result = []
  16. # Initialize the heap with the first record
  17. heapq.heappush(heap, (records[0].date, records[0]))
  18. for i in range(1, len(records)):
  19. # Compare the current record's date with the smallest date in the heap
  20. date, record = heapq.heappop(heap)
  21. if records[i].date > date:
  22. # Current record is later than the smallest date in the heap
  23. heapq.heappush(heap, (records[i].date, records[i]))
  24. else:
  25. # Current record is earlier than or equal to the smallest date in the heap
  26. heapq.heappush(heap, (date, record))
  27. heapq.heappush(heap, (records[i].date, records[i]))
  28. # Extract records from the heap in sorted order
  29. while heap:
  30. date, record = heapq.heappop(heap)
  31. result.append(record)
  32. return result

Add your comment