JavaScript 实现选择排序

思路

升序排序为例:

  1. 找到数组中的最小值,将其放置在数组第一位
  2. 找到数组中第二小的值,将其放置在数组第二位
  3. 以此类推,执行n-1轮就可以完成排序

升序选择排序动画演示如图所示:

时间复杂度:O(n2)

实现

现有数组[7, 5, 4, 15, 3, 9, 6, 12],进行升序排序:

Array.prototype.selectionSort = function() {
    
    
    // 重复(元素个数-1)次
    for (let i = 0; i < this.length - 1; i++) {
    
    
        // 把第一个没有排序过的元素设置为最小值
        let indexMin = i;
        // 遍历每个没有排序过的元素
        for (let j = i; j < this.length; j++) {
    
    
            // 如果遍历时出现元素小于现在的最小值
            if (this[j] < this[indexMin]) {
    
    
                // 将此元素设置为新的最小值
                indexMin = j;
            }
        }
        // 遍历结束后,将最小值和第一个没有排序过的位置交换
        if (indexMin !== i) {
    
    
            let temp = this[i];
            this[i] = this[indexMin];
            this[indexMin] = temp;
        }
    }
};

const arr = [7, 5, 4, 15, 3, 9, 6, 12];
arr.selectionSort();
console.log(arr);

执行结果:

猜你喜欢

转载自blog.csdn.net/Jack_lzx/article/details/114876873
今日推荐