如何通过索引数组重新排列数组(证明)?

时间:2016-06-09 10:39:16

标签: javascript arrays algorithm

给定一个数组arr和一个索引ind数组,以下算法就地重新排列arr以满足给定的索引:

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

例如:

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"]

证明该算法有效的最有说服力的方法是什么?

1 个答案:

答案 0 :(得分:4)

此算法不起作用,足以显示反例:

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

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

工作替代方案可能是

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