In-line Array Element Swapping

Have you ever taken a coding class where they explain to you how to swap two elements of an array? Cuz I have, and most of the time they explain it in this sort of manner:

Assume we have an array arr = {5, 4, 3, 2, 1} to swap any two elements i and j of an array such as this, you do the following:

temp = arr[i]
arr[i] = arr[j]
arr[j] = temp

Because this is straight forward right?  Well yes, but what if you didn't want to have to make a variable called temp to do it?  Most instructors inform their students that there exists an in-line option which doesn't require any extra maneuvers, but rarely explain how it's performed.  Well, I've figured it out.

Suppose we want to swap the two elements 5 and 4 from the list above, right off the bat, if you try to swapt the two you'd realize that in the process of assigning arr[i] = arr[j] the value of arr[i] would be overriden, so how can we assign two values two a single value in an array so that we can still retrieve them both? The answer, is math.

Suppose we select some number 6 which is larger an any element in arr, and we assign such that:
arr[i] = arr[i] + (arr[j] * 6)
Note that in our case arr[i] = 5 + 4 * 6 = 29
Now check this out:
29 % 6 == 5
and
29 // 6 == 4 (where // indicates integer division)

Both values are now stored in a single value! Well, it turns out this method works for any pair of numbers as long as the multiplier (6 in our case) is larger than every element of the array in question.

This means that your swapping method can be changed to:

arr[i] = arr[i] + (arr[j] * maxele)
arr[j] = arr[i] % maxele
arr[i] = arr[i] // maxele

Where maxele is the a number that is larger than every element in the array.

And voila! An array swapping method that requires no extra variables!

Comments

Popular posts from this blog

Using Custom Datasets with Tensorflow's Object Detection API

The (Ultimate) Guide to Installing TensorFlow

Heapsort and heaps