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();
以上就是JavaScript选择排序的实现,希望对大家有所帮助。更多Javascript学习指路:
推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务