Skip to content Skip to sidebar Skip to footer

How To Rearrange An Array By Indices Array (proof)?

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[

Solution 1:

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;
      }
    }
  }
}

Post a Comment for "How To Rearrange An Array By Indices Array (proof)?"