Skip to content

前端算法:冒泡排序 #9

@wsdo

Description

@wsdo

文章永久链接:https://fe8.cn/question/629cd1352d155

原理

每一趟循环只能确定将一个数归位。即第一趟只能确定将末位上的数归位,第二趟只能将倒数第 2 位上的数归位,依次类推下去。如果有 n 个数进行排序,只需将 n-1 个数归位,也就是要进行 n-1 趟操作。而 “每一趟 ” 都需要从第一位开始进行相邻的两个数的比较,将较大的数放后面,比较完毕之后向后挪一位继续比较下面两个相邻的两个数大小关系,重复此步骤,直到最后一个还没归位的数。

Array.prototype.bubbleSort = function () {
    for (let i = 0; i < this.length - 1; i += 1) { // 控制比较次数,共n-1次
        for (let j = 0; j < this.length - 1 - i; j += 1) { // 控制相邻元素进行比较
            if (this[j] > this[j + 1]) {
                const temp = this[j];
                this[j] = this[j + 1];
                this[j + 1] = temp;
            }
        }
    }
};

const arr = [5, 4, 3, 2, 1];
arr.bubbleSort();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions