首页 > 文章列表 > JavaScript选择排序的实现

JavaScript选择排序的实现

JavaScript 选择排序
371 2022-08-06

1、从未排序序列中找到元素,放在排序序列的末尾,重复上述步骤,直到所有元素排序完成。

2、找到数组中的最小值,选择并放在第一位。

3、然后找到第二个小值,选择它,放在第二位。

4、以此类推,执行n-1轮。

实例

Array.prototype.selectionSort = function () {
  for (let i = 0; i < this.length - 1; i += 1) {
    let indexMin = i;
    for (let j = i; j < this.length; j += 1) {
      if (this[j] < this[indexMin]) {
        indexMin = j;
      }
    }
    if (indexMin !== i) {
      const temp = this[i];
      this[i] = this[indexMin];
      this[indexMin] = temp;
    }
  }
};
 
const arr = [5, 4, 3, 2, 1];
arr.selectionSort();

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。