0

I have been viewing the article Cycle sort on Wikipedia which has an implementation in python which I don't understand.

https://en.wikipedia.org/wiki/Cycle_sort

What do the lines like this do?

array[pos], item = item, array[pos]
NeDark
  • 1,212
  • 7
  • 23
  • 36
  • 1
    Possible duplicate of [Is there a standardized method to swap two variables in Python?](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – hnefatl Aug 03 '18 at 22:37
  • 1
    Without knowing much about Python, I'd guess this is a swap of `item` and `array[pos]` – Michael Dorgan Aug 03 '18 at 22:38
  • As an additional clarification, it's a swap, but since `item` is a local variable, from the view point of cycle sort, where the goal is to minimize the number of writes, the only "write" is to `array[pos]`. – rcgldr Aug 04 '18 at 01:03

1 Answers1

0

Here's an interactive Python session which answers your question (in short: the array[pos] gets swapped with the item):

In [1]: array = [1,2,3]

In [2]: pos = 0

In [3]: item = 4

In [4]: array[pos], item = item, array[pos]

In [5]: array
Out[5]: [4, 2, 3]

In [6]: item
Out[6]: 1
Bob
  • 5,809
  • 5
  • 36
  • 53