Click here to Skip to main content
14,086,389 members
Rate this:
Please Sign up or sign in to vote.
I need to build an algorithm that can look at X number of records which have overlapping dates in them and organize and re-insert those date values in a chronological sequence.
The table has a record like this:

Start Date End Date Value
1/1/2019 12/31/2099 10

When a new record like this is inserted,
5/1/2019 5/31/2019 25

The algorithm should organize the records like this and insert it into a new table:
1/1/2019 4/30/2019 10
5/1/2019 5/31/2019 25
6/1/2019 12/31/2099 10

The original table should not be modified, i.e. no reinserting/reordering of records in that original table.

Any tips on the most efficient way to accomplish this? Not looking for database specific solutions.. programming only.

What I have tried:

Tried whiteboarding it, but it seemed like i'm ending up with way too many passes thru the data before coming close to a possible solution. Wasn't sure if I was missing a more obvious algorithm out there.
Updated 7-Apr-19 18:12pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Not sure if I understand the question correctly and if this is about RDBMS, but...

In majority of cases the data is not sorted in the table, but sorted upon fetching. The DBMS reuses free space and some DBMS may relocate rows when needed so depending on the solution sorting may be impossible to do on a physical level. Also there is no way to fetch the data using the physical order.

Based on your example, why not simply use ORDER BY clause using two fields. For example
FROM ...
ORDER BY StartDate, EndDate

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190518.1 | Last Updated 8 Apr 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100