Search code examples
arrayssortingadhoc

Is it possible to sort an array using one temporary variable/space?


Suppose an array is given by a1, a2, ..., ak, _ , a(k+1), ..., an. Here an underscore (_) represents blank space. We can move any array element to this space. We can repeat this operation any number of times. Is it possible to sort every array with one such blank space?


Solution

  • Yes it is possible.

    A sorted array is just a particular permutation of that array.

    Any permutation can be arrived at by a sequence of individual swaps.

    And a swap can be implemented with a single temporary element.

    (It's actually possible to sort an array of integral types without a temporary, using XOR operations).