A swap mathod on the Array Class

Forums for specific tips, techniques and example code
ConvertFromOldNGs
Posts: 5321
Joined: Wed Aug 05, 2009 5:19 pm

A swap mathod on the Array Class

Postby ConvertFromOldNGs » Fri Aug 07, 2009 2:16 pm

by Paul Mathews >> Wed, 14 Jul 1999 8:33:33 GMT

Would welcome any improvements by Craig, Dean et al on this method
which has implementation of drag and drop reordering of data by users straightforward.

swap(pFrom : MemberType ; pTo : MemberType) updating;

// Date: 01 January 1999
// User: paulm


// Swap to entries in an array with each other.
vars
vFrom : Integer;
vTo : Integer;begin


vFrom := self.indexOf(pFrom);
vTo := self.indexOf(pTo);

if vFrom < vTo then
self.removeAt(vTo);
self.removeAt(vFrom);
self.insert(vFrom,pTo);
self.insert(vTo,pFrom);

else
self.removeAt(vFrom);
self.removeAt(vTo);
self.insert(vTo,pFrom);
self.insert(vFrom,pTo);
endif;
end;

Paul Mathews
pem@cmsystemsgroup.com.au
Phone: [612] (99717384) Fax[612] (99711679)
(Dee Why,Sydney,Australia)

Please visit our homepage cmsystemsgroup.com.au.

ConvertFromOldNGs
Posts: 5321
Joined: Wed Aug 05, 2009 5:19 pm

Re: A swap mathod on the Array Class

Postby ConvertFromOldNGs » Fri Aug 07, 2009 2:16 pm

by Craig Shearer >> Thu, 15 Jul 1999 20:58:14 GMT

Hi Paul

Your method seems unnecessarily complicated... you don't have to do the removes and inserts (and they're probably quite expensive operations).

Here's what I came up with:


swap(member1, member2: MemberType);

vars
mem1Pos,
mem2Pos : Integer;
begin

exclusiveLock(self);

mem1Pos := indexOf(member1);
mem2Pos := indexOf(member2);

self[mem1Pos] := member2;
self[mem2Pos] := member1;

epilog
unlock(self);

end;


The method assumes that it will find each member in the array. If it can't then you'll get an exception on the self[mem1Pos] or self[mem2Pos] lines.

The lock operations are there to avoid deadlock as mentioned in a previous article.

While the above method will work, it requires two sequential searches of the array to find the members. Since you're dealing with an array, you most likely know the positions of the entries you want to swap anyway, so if you alreay know the positions of the entries then just do a traditional swap:

temp := array[pos1];
array[pos1] := array[pos2];
array[pos2] := temp;


Craig.


Return to “Tips and Techniques”

Who is online

Users browsing this forum: No registered users and 21 guests