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
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.