I have the following task:
Given an array
a
holding positions and arrayb
holding values, order the elements in the arrayb
according to the positions in the arraya
. For the input:a = [3, 0, 1, 2]; b = ['a', 'b', 'c', 'd'];
the output should be
[ 'b', 'c', 'd', 'a' ]
I have written a simple algorithm which simply an item into the specified position by swapping:
// a.lenght -1 since the last element will end up in the correct vacant position
for (let i = 0; i < a.length - 1; i++) {
const position = a[i];
swap(b, i, position);
}
Although I've tested it and it seems to produce correct results, I can't figure how to prove it works correctly. Can anyone please help with reasoning?