Brain Dump

Swap

Tags
algorithm

A simple algorithm to swap two elements in an array.

def swap(arr, k, l):
    tmp = arr[k]
    arr[k] = arr[l]
    arr[l] = tmp
Code Snippet 1: Swap implementation.

A lot of hardware has dedicated commands to do this, but many higher level languages don't expose this abstraction. Instead we commonly save the current value in a temporary variable, update the current value of the first element and then set the second element to the temp value.