In-place algorithms

By Martin McBride, 2017-01-03
Tags: sort in-place
Categories: algorithms sort

Sort algorithms usually have:

  • One input - an array of unsorted elements
  • One output - an array of the same elements sorted in order

There are other algorithms which work in a similar way. For example, a shuffle algorithm takes an array of elements which are in order, and mixes them up in a random order, just like shuffling a pack of cards. This algorithm is used in computer card games such as Solitaire.

Using two arrays

The natural way to write an algorithm like this would be to use 2 arrays, an input array containing the initial values, and an output array to hold the sorted values. The output array would start off empty (e.g. filled with zeros).

in = [9, 3, 6, 5, 2, 1, 8]
out = [0 , 0, 0, 0, 0, 0, 0]

After sorting, the output array would contain the elements in correct order:

in = [9, 3, 6, 5, 2, 1, 8]
out = [1, 2, 3, 5, 6, 8, 9]

In-place solutions

Using two arrays could be a problem is there is a very large amount of data, because it requires twice as much memory. We might prefer a version of the algorithm which works "in-place" - the calculation is performed by moving elements around in a single array. We start with:

in = [9, 3, 6, 5, 2, 1, 8]

And end up with this (with no second array required:

in = [1, 2, 3, 5, 6, 8, 9]

Many common search algorithms can be carried out in place.

See also

Sign up to the Creative Coding Newletter

Join my newsletter to receive occasional emails when new content is added, using the form below:

Popular tags

555 timer abstract data type abstraction addition algorithm and gate array ascii ascii85 base32 base64 battery binary binary encoding binary search bit block cipher block padding byte canvas colour coming soon computer music condition cryptographic attacks cryptography decomposition decryption deduplication dictionary attack encryption file server flash memory hard drive hashing hexadecimal hmac html image insertion sort ip address key derivation lamp linear search list mac mac address mesh network message authentication code music nand gate network storage none nor gate not gate op-amp or gate pixel private key python quantisation queue raid ram relational operator resources rgb rom search sort sound synthesis ssd star network supercollider svg switch symmetric encryption truth table turtle graphics yenc