1

Given an array arr and an array of indices ind, the following algorithm rearranges arr in-place to satisfy the given indices:

function swap(arr, i, k) {
  var temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
}

function rearrange(arr, ind) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (ind[i] !== i) {
      swap(arr, i, ind[i]);
      swap(ind, i, ind[i]);
    }
  }
}

For example:

var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [ 4,   0,   5,   2,   1,   3 ];

rearrange(arr, ind);

console.log(arr); // => ["B", "E", "D", "F", "A", "C"]

What's the most convincing way to prove that the algorithm works?

9
  • Write a bunch of test cases and show that they pass...?! Commented Jun 9, 2016 at 10:41
  • 2
    why do you think that this algorithm works at first place? Shouldn't the output be ["E", "A", "F", "C", "B", "D"] on the basis of indices? Commented Jun 9, 2016 at 10:44
  • 1
    @gurvinder372 ...? Why? Commented Jun 9, 2016 at 10:47
  • 1
    @deceze Unless I have missed something, rearranging ["A", "B", "C", "D", "E", "F"] as per [4, 0, 5, 2, 1, 3] should give ["E", "A", "F", "C", "B", "D"] right? Since E is at the fourth index and A is at 0th index..? Commented Jun 9, 2016 at 10:49
  • 2
    @gurvinder372 Not sure what logic you're applying there... the second array seems to contain the desired indices for values of the same key in the first array. arr[0] should go to the index ind[0], which is 4, which means 'A' should go to position 4. Commented Jun 9, 2016 at 10:51

1 Answer 1

4

This algorithm does not work, it's enough to show a counter-example:

var arr = ["A", "B", "C", "D"];
var ind = [  2,   3,   1,   0];

rearrange(arr, ind);
console.log(arr); // => ["C", "D", "A", "B"]

A working alternative may be

function swap(arr, i, k) {
  var temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
}

function rearrange(arr, ind) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (ind[i] !== i) {
      swap(arr, i, ind[i]);
      swap(ind, i, ind[i]);
      if (ind[i] < i) {
        i = ind[i]-1;
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, wow! Thanks a lot for presenting a simple counter example!
I created a new question. You might want to add your suggestion there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.