There are two ways to handle this, depending on usage. But first, you should probably be using a TList
instead of an array. It has methods for handling insertions and deletions and keeping things in order.
If you're performing a lot of inserts at a time, you'll want to use the dirty insert algorithm, which works like this:
The list comes with an associated flag, a boolean value called
Dirty
. When you insert something, stick it on the end of the list, and setDirty
toTrue
. When you go to read from the list, first check theDirty
flag, and if its value isTrue
, sort the list, setDirty := False;
and then do the read. With a lot of inserts, this is much faster than keeping the list in sorted order as you insert.
However, if you're not likely to be doing several inserts at a time, it's cheaper to maintain the list in sorted order. You don't need to do that by calling Sort
every time, though. You do it like this:
Because your data is already sorted, you can find the correct position for a new value by using a binary search. Have the Insert operation use a binary search to determine where the new value should go, insert it there, and your list remains in sorted order.
As for deletes, you shouldn't have to worry about sorting order. Just call Delete
on your TList
, and if it started out sorted, removing an item won't change that.