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排序的三种方法,感谢您的观看。

你可能感兴趣的:(javascript,前端)