JavaScript implements bubble sort

Ideas

Take ascending order as an example:

  1. Compare all adjacent elements in turn, if the first one is greater than the second, swap them
  2. After one round, the last number can be guaranteed to be the largest
  3. The execution n-1round can complete the sorting

The ascending bubble sort animation demonstration is shown in the figure:

Time complexity : O(n 2 )

achieve

Existing array [7, 5, 4, 15, 3, 9, 6, 12], sort in ascending order:

Array.prototype.bubbleSort = function() {
    
    
    // 重复(元素个数-1)次
    for (let i = 0; i < this.length - 1; i++) {
    
    
        // 从0开始遍历还没有排序过的元素
        for (let j = 0; j < this.length - 1 - i; j++) {
    
    
            // 如果当前元素比下一个大
            if (this[j] > this[j + 1]) {
    
    
                // 交换他们的位置
                let temp = this[j];
                this[j] = this[j + 1];
                this[j + 1] = temp;
            }
        }
    }
};

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

Results of the:

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/114876827