• js排序都有哪些方法?


    1、方法一:sort方法排序(a-b正向        b-a反向)

            var arr=[3,1,5,8,28]

            //正向 a-b

            var arr1=arr.sort(function  (a,b) {

                    return a-b;

            })

            console.log(arr1) //[1,3,5,8,28];

            //反向 b-a

            var arr2=arr.sort(function  (a,b) {

                    return b-a;

            })

            console.log(arr2) //[28,8,5,3,1]

    2、方法二:冒泡排序

            var arr=[3,1,5,8,28]

                    function sortArr(arr){

                            for(let i=0; i

                              //arr.length-i 保证每次比较都会少比较一位(因为最大的一位已经找出,放在了最后)

                                       for(let j=0; j

                                              if(arr[j] > arr[j+1]){

                                                      let temp = arr[j];

                                                      arr[j] = arr[j+1];

                                                      arr[j+1] = temp;

                                              }

                                        }

                                    }

                                            return arr

                            }

                             var arr1 = sortArr(arr)

                              console.log(arr1)

    3、选择排序

            var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5];

                    function selectSort(arr){

                        for(var i=0;i

                            //设置当前范围最小值和索引

                            var min = arr[i];

                            var minIndex = i;

                            //在该范围选出最小值

                            for(var j=i+1;j

                               if(min>arr[j]){

                                       min = arr[j];

                                       minIndex = j;

                                }

                            }

                            //将最小值插入

                            arr.splice(i,0,min);

                            //将原来位置的最小值删除

                            arr.splice(minIndex+1,1);

                    }

                    return arr

            }

            var arr1=selectSort(arr)

            console.log(arr1)

    总结:以上就是Js排序的三种方法,感谢您的观看。

  • 相关阅读:
    【优化调度】粒子群算法求解水火电调度优化问题【含Matlab源码 1181期】
    在QGIS中加载显示3DTiles数据
    【学习笔记之我要C】预处理
    业务限制模型例题
    有哪些好用的程序员接私活平台?
    Kindling-OriginX 在快手 Staging 环境的异常诊断效果分享
    深入浅出大数据:88页Hadoop实战手册,重视实操易于理解
    11.22 - 每日一题 - 408
    10 【异步组件 组合式函数(hooks)】
    爬虫神器Selenium傻瓜教程,看了直呼牛掰
  • 原文地址:https://blog.csdn.net/Asrty/article/details/127836529