Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutation of a vector

suppose I have a vector:

 0  1  2  3  4  5
[45,89,22,31,23,76]

And a permutation of its indices:

[5,3,2,1,0,4]

Is there an efficient way to resort it according to the permutation thus obtaining:

[76,31,22,89,45,23]

Using at most O(1) additional space?

like image 398
tunnuz Avatar asked Feb 07 '09 14:02

tunnuz


1 Answers

Yes. Starting from the leftmost position, we put the element there in its correct position i by swapping it with the (other) misplaced element at that position i. This is where we need the O(1) additional space. We keep swapping pairs of elements around until the element in this position is correct. Only then do we proceed to the next position and do the same thing.

Example:

[5 3 2 1 0 4] initial state

[4 3 2 1 0 5] swapped (5,4), 5 is now in the correct position, but 4 is still wrong

[0 3 2 1 4 5] swapped (4,0), now both 4 and 0 are in the correct positions, move on to next position

[0 1 2 3 4 5] swapped (3,1), now 1 and 3 are both in the correct positions, move on to next position

[0 1 2 3 4 5] all elements are in the correct positions, end.

Note:

Since each swap operation puts at least one (of the two) elements in the correct position, we need no more than N such swaps altogether.

like image 171
Zach Scrivena Avatar answered Oct 13 '22 13:10

Zach Scrivena