一些排序的方法

快速排序

var ary = [3,2,1]
         function quick(ary) {
             if(ary.length<=1){
                 return ary
             }
             let centerIndex =  Math.floor(ary.length/2);
             let centerValue = ary.splice(centerIndex, 1) 
            let leftAry = [];
            let rightAey = [];
             for(var i =0; i<ary.length;i++){
                 var cur = ary[i];
                 if(ary[i]<centerValue){
                     leftAry.push(cur)
                 }
                 else {
                     rightAey.push(cur)
                 }
             }
             return quick(leftAry).concat(centerValue, quick(rightAey))
         }
        console.log(quick(ary))

冒泡排序

var ary= [12, 23, 14, 25, 11, 13];
    function fn(ary){
        for(var i=0;i<ary.length-1;i++){
                for(var j=0;j<ary.length-1-i;j++){
                    if(ary[j] < ary[j+1]){
                        var temp = '';
                        temp = ary[j];
                        ary[j] = ary[j+1];
                        ary[j+1] = temp
                    }
                }
        }
        return ary
    }
    console.log(fn(ary))
    console.log(ary)

新插入排序

var ary = [15, 13, 14, 11, 23, 19];
        function insert(ary) {
            let newAry = []; 
            newAry.push(ary[0]);
            for (var i = 1; i < ary.length; i++) {
               var cur = ary[i];
               for(var j = newAry.length-1;j>=0;j--){
                   if(cur>newAry[j]){
                       newAry.splice(j+1, 0, cur);
                       break;
                   }
                   if(j === 0){
                       newAry.unshift(cur)
                   }
               }
            }
            return newAry
        }
        console.log(insert(ary))

数组去重

let ary = [1,21,2,3,8,2,2];
    for(var i=0;i<ary.length;i++){
        for(var j=i+1;j<ary.length;j++){
            if(ary[i] === ary[j]){ 
                ary.splice(j,1);
                j--;
            }
        }
    }
    console.log(ary);
var arr = [1,2,2,3,4] 
var set = new Set(arr) // {1,2,3,4}
var newArr = Array.from(set)
console.log(newArr)
var arr=['h','e','l','l','o','2',1,2,1,3,2];
arr.sort(function(a,b) { return a-b; } );
for(var i=0; i<arr.length-1; i++){
   if(arr[i] === arr[i+1]){
	arr.splice(i,1);
	i--;
   }
}
console.log(arr)

Debugger 是个好东西,要学会用它。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值