玫瑰不香

导航

踩坑日记 - 排序算法之冒泡排序

1、冒泡排序

一种简单又稳定的,也是原地的排序算法。每次的遍历都是将遍历过程中最大或最小的元素沉入最后,故此叫冒泡排序

2、排序原理3、排序步骤:

遍历相邻两元素,交换符合条件的两个元素。

3、排序步骤

  1) 外循环是遍历每个元素,每次都放置好一个元素;

  2) 内循环是比较相邻的两个元素,把大的元素交换到后面;

  3) 等到第一步中循环好了以后也就说明全部元素排序好了;

4、复杂度

  1)平均:

    时间复杂度: O(n^2);空间复杂度:O(1)

  2)最优:已经排好序的序列

    时间复杂度: O(n^2);空间复杂度:0

  3)最差:序列正好与结果相反

    时间复杂度: O(n^2);空间复杂度:O(n)

 

5、例子

  代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>排序 -  冒泡排序</title>
</head>
<body>

    <div>
        这是数组原序列:[20, 25, 1, 2, 78, 100, 56, 5, 22,66]
    </div>
    
</body>
</html>

<script>
    // const originArr = [20, 25, 1, 2, 78, 100, 56, 5, 22,66]; // 普通
    // const originArr = [1, 2, 5, 20, 22, 25, 56, 66, 78, 100];  // 最优
    const originArr = [100, 78, 66, 56, 25, 22, 20, 5, 2, 1];   // 最差
    const newArr = JSON.parse(JSON.stringify(originArr));
    const len = originArr.length;
    const len2 = len - 1;
    // console.log('这是数组原序列:[20, 25, 1, 2, 78, 100, 56, 5, 22,66]')
    // console.log('这是数组原序列:[1, 2, 5, 20, 22, 25, 56, 66, 78, 100]')
    console.log('这是数组原序列:[100, 78, 66, 56, 25, 22, 20, 5, 2, 1]')
    for(let i = 0; i < len; i++){
        for(let j = 0; j < len - i - 1; j++){
            if (originArr[j] > originArr[j + 1]) {
                console.error('我是元素交换')
                const temp = originArr[j + 1];
                originArr[j +1] = originArr[j];
                originArr[j] = temp;
            }
        }
        console.log('这是第' + (i + 1) + '次循环的结果:' + JSON.parse(JSON.stringify(originArr)))
    }
    console.log('这是最终结果:' + originArr)

</script>

 

  1)普通

  2)最优

     

  3)最差

      

 

参考:https://blog.csdn.net/qq_39741605/article/details/80821595?utm_medium=distribute.pc_relevant_t0.none-task-blog-blogcommendfrommachinelearnpai2-1.add_param_iscf&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-blogcommendfrommachinelearnpai2-1.add_param_iscf

https://blog.csdn.net/weixin_43419883/article/details/88418730

 

posted on 2020-09-14 01:26  布娃娃  阅读(206)  评论(0编辑  收藏  举报