Re: Sorting an array. Fastest way.
- From: Martin Gregorie <martin@xxxxxxxxxxxxxxxxxxx>
- Date: Sun, 17 Feb 2008 00:39:03 +0000
Andreas Leitgeb wrote:
Lew <lew@xxxxxxxxxxxxx> wrote:A TreeMap, which implements a red-black balanced binary tree, will give reasonable performance with any size of data set. Its performance isn't degraded by loading pre-ordered data: this is a problem with simple (unbalanced) unbalanced binary tree algorithms. Red-black trees are never blindingly fast, but don't have performance black holes either.Sanny wrote:I have an array of int.
Given an initially sorted collection, the first element is
modified/replaced, and the collection needs to be re-sorted.
For an array, this means the described "algorithm":I find using binarydearch the position "pos" where the ist elewment
need to go.
Then I do arraycopy to shift all elements by 1 and copy the 1st
element to the "pos" position.
Since the expensive part is shifting, it appears obvious that a
collection that allows easy inserting/removal of items may be
better, but unfortunately I think that such structures do not
behave as well with binary search (which requires random index
addressing)
I'm not entirely sure about other possible disadvantages, but
it looks like TreeMap or TreeSet might be an optimal collection
for OP's needs.
Operations on a TreeMap won't be as fast as on an array, but they don't degrade badly for a small dataset and do become spectacularly fast for extremely large data sets. When the tree is very small the search degenerates toward a sequential search, but as the data set grows the number of key comparisons drops dramatically - it can find a match from 8388608 entries with only 23 key comparisons. The only drawback is that an amendment that changes the key MUST be a deletion followed by an insert to maintain the tree's ordering, so an amendment will take approximately twice as long as a search.
A binary search on an ordered array will be quicker than walking the tree, but any array insertion involves either resorting the entire array or moving all higher keys up a cell to make space for the new value. Deletions and key amendments have similar large overheads for large data sets.
Finding the insertion point and making the insertion in a tree is much faster. Same applies to a deletion. A key amendment is simply a deletion plus an amendment.
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |
.
- References:
- Sorting an array. Fastest way.
- From: Sanny
- Re: Sorting an array. Fastest way.
- From: Lew
- Re: Sorting an array. Fastest way.
- From: Andreas Leitgeb
- Sorting an array. Fastest way.
- Prev by Date: Re: Autoboxing confusion!!!
- Next by Date: Re: Sorting an array. Fastest way.
- Previous by thread: Re: Sorting an array. Fastest way.
- Next by thread: Re: Sorting an array. Fastest way.
- Index(es):
Relevant Pages
|
Loading