python 与 javascript 中的插入排序

insertion sort in python vs javascript

我使用 python 和 javascript 实现了插入排序。由于某些奇怪的原因,JS 代码有效,而 python 代码无效。两种实现都应该做同样的事情。我遍历了每一行代码,找不到两者之间的区别。看看你是否能发现 python 代码的不同之处。

Javascript代码:

function insertionSort(nums) {

  for (let i=0; i<nums.length; i++) {
    const value = nums[i];
    let hole = i;

    while (hole >= 0 && nums[hole-1] > value) {
      nums[hole] = nums[hole-1];
      hole = hole - 1;
    }
    nums[hole] = value;
  }
  return nums;
}


const sorted = insertionSort([5,2,1,3,6,4]);
console.log(sorted);

Python代码:

def insertion_sort(nums):
  for i in range(0,len(nums)):
    value = nums[i]
    hole = i

    while hole >= 0 and nums[hole-1] > value:
      nums[hole] = nums[hole-1]
      hole = hole - 1

    nums[hole] = value
  return nums

sorts = insertion_sort([5,2,1,3,6,4])
print(sorts) 
  nums[hole] = nums[hole-1]

如果hole == 0nums[hole-1]变为nums[-1],即获取列表的最后一个元素。这不是它在 Javascript.

中的作用

Python 和 javascript 对 someList[-1] 的作用有不同的看法。

在您上面的代码中,您计算​​ nums[hole-1]。当 hole 为零时,您编写循环的方式可以是 nums[-1]。在 python 代码中,它获取列表的最后一个元素。在 javascript 代码中,这是未定义的。这对下一部分的含义有重大影响:nums[hole-1] > value 的含义。

最终hole的值为0时不需要计算while hole >= 0 and nums[hole-1] > value,所以可能将>=改为>会是个不错的选择。