[AccessD] Swap two elements in an array
Paul Wolstenholme
Paul.W at industrialcontrol.co.nz
Thu Aug 18 16:26:34 CDT 2022
There are answers that work without a temporary variable in some
circumstances. I've used those in the world of programming small
microprocessors but I don't think they are likely to be your best solution
here.
The following sequence generally works on small microprocessor compilers
but I've never tried it in VBA:
A = A XOR B
B = A XOR B
A = A XOR B
The following should also work on integer types (floating point can have
rounding errors) IF any overflow is not trapped and it results in rollover
(or alternatively if there is no overflow):
A = A + B
B = A - B
A = A - B
I think the temporary variable is preferable.
When you talk about 'the best way' that could involve using pointers to the
array elements so the compiler evaluates the memory locations once. You
might want speed or you might want simplicity.
Paul Wolstenholme
On Fri, 19 Aug 2022 at 04:16, Arthur Fuller <fuller.artful at gmail.com> wrote:
> Thanks, Stuart.
>
> After sending my message, I rolled my own, using exactly the same technique
> as you -- couldn't think of a way around the temp variable.
>
> On Thu, Aug 18, 2022 at 9:41 AM Stuart McLachlan <stuart at lexacorp.com.pg>
> wrote:
>
> > Since VBA doesn't have a SWAP function, you have to do it with a
> temporary
> > variable
> > Assuming it's a one dimensional array, something like:
> >
> > Temp = Arr(2) : Arr(2) = Arr(4) : Arr(4) = Temp
> > If you define Temp as a Variant, you can use it with any type of array.
> >
> > If it's a multi-dimensional array, you have to sway each dimension:
> > Temp = Arr(1,2) : Arr(1,2) = Arr(1,4) : Arr(1,4) = Temp
> > Temp = Arr(2,2) : Arr(2,2) = Arr(2,4) : Arr(2,4) = Temp
> > Temp = Arr(3,2) : Arr(3,2) = Arr(3,4) : Arr(3,4) = Temp
> > ...
> >
> >
> > On 18 Aug 2022 at 8:35, Arthur Fuller wrote:
> >
> > > What is the best way to swap two elements in an array? Typically they
> > > are adjacent but ideally I want a method that can swap any two
> > > elements.
> > >
> > > --
> > > Arthur
> > > --
> > > AccessD mailing list
> > > AccessD at databaseadvisors.com
> > > https://databaseadvisors.com/mailman/listinfo/accessd
> > > Website: http://www.databaseadvisors.com
> > >
> >
> >
> > --
> > AccessD mailing list
> > AccessD at databaseadvisors.com
> > https://databaseadvisors.com/mailman/listinfo/accessd
> > Website: http://www.databaseadvisors.com
> >
>
>
> --
> Arthur
> --
> AccessD mailing list
> AccessD at databaseadvisors.com
> https://databaseadvisors.com/mailman/listinfo/accessd
> Website: http://www.databaseadvisors.com
>
More information about the AccessD
mailing list