On Sep 30, 2006, at 3:27 AM, Dr Gerard Hammond wrote:
At 11:02 PM -0400 29/9/06, Walter Purvis wrote:
> -----Original Message-----
Subject: How do you sort Object arrays?
The standard way of sorting objects, or anything really, is to use
Charles
Yeomans' excellent sorting library
http://declaresub.com/Code/SortLibrary.zip
(If RB was Python, this would have been rolled into the standard
distribution by now.)
Maybe I am just dumb, but I just don't understand this sorting
library works, or how I can finagle it into my own apps with my own
data objects.
Perhaps someone can write an article on it for this list or
RBDeveloper (or RBLibrary). I'd pay for it, so that I would feel
less stupid ;-)
--
I'm a little surprised to hear this; I'd certainly be willing to
write a tutorial. The SortLibrary class has two methods, Sort(obj()
as Object, c as Comparator) and StableSort(obj() as Object, c as
Comparator). Here is an example.
Suppose you want to sort an array of Date objects. You define a
class DateComparator that implements the Comparator interface. This
interface specifies a function that defines object comparison. Here,
you might use the following.
Function Compare(obj1 as Object, obj2 as Object) as Integer
return Date(obj1).TotalSeconds - Date(obj2).TotalSeconds
End Function
Then, given an array DateList() as Date, you sort it as follows.
SortLibrary.Sort DateList, new DateComparator
Now, it would also be possible to do this using Array.SortWith as
follows.
dim keyList(-1) as Double
redim keyList(UBound(dateList))
for i as Integer = 0 to UBound(dateList))
keyList(i) = dateList(i).TotalSeconds
next
keyList.SortWith dateList
And this sort is an order of magnitude faster than mine -- 4 ticks v.
110 ticks for a 100,000 object array. SortWith trades extra memory
and extra swaps for the ability to sort a Double array, which can be
done very, very quickly. SortLibrary has the overhead of virtual
function calls for every comparison.
Interestingly, I was able to speed up my sort by about 30% by
rewriting the Compare code to avoid Double-to-Integer conversion as
follows.
Function Compare(obj1 as Object, obj2 as Object) As Integer
dim x as Double = Date(obj1).TotalSeconds - Date(obj2).TotalSeconds
if x > 0.0 then
return 1
elseif x < 0.0 then
return -1
else
return 0
end if
End Function
Charles Yeomans
_______________________________________________
Unsubscribe or switch delivery mode:
<http://www.realsoftware.com/support/listmanager/>
Search the archives of this list here:
<http://support.realsoftware.com/listarchives/lists.html>