js 对集合排序 , 冒泡排序 sort排序

 
var listDoctorTime= [ { "id": 1, "name": "张三", "index": "100" },
           { "id": 2, "name": "李四", "index": 120 },
           { "id": 3, "name": "王武", "index": 80 },
           { "id": 4, "name": "二狗", "index": 40 },
           { "id": 5, "name": "屎蛋", "index": 160 }
            ];

方法1:冒泡排序
bubbleSortlistDoctorTime(listDoctorTime);
方法2: sort方法 

listDoctorTime.sort(function(a,b){
          return a.index-b.index;
       });

//遍历
 for(var w=0;w<listDoctorTime.length;w++){
         console.log("listDoctorTime[w].index=="+listDoctorTime[w].index);
     }
输出结果:listDoctorTime[w].index==40

           listDoctorTime[w].index==80

           listDoctorTime[w].index==120

           listDoctorTime[w].index==160

//冒泡排序  
        function bubbleSortlistDoctorTime(listDoctorTime){
             if(listDoctorTime.length>1){
                 for(var i=0;i<listDoctorTime.length-1;i++){//外层控制循环的次数
                     for(var j=0; j<listDoctorTime.length-i-1;j++ ){//内层控制比较多少次
                         if(parseInt(listDoctorTime[j+1].index) < parseInt(listDoctorTime[j].index)){
                             var doctorTime=listDoctorTime[j+1];
                             listDoctorTime[j+1]=listDoctorTime[j];
                             listDoctorTime[j]=doctorTime;
                         }
                     }
                 }
             }
             return listDoctorTime;
        }
     

//简单集合冒泡排序    
 
var nums = new Array(8,9,1,2,10);
function test(){
            //进行几轮比较,确定几个位置
            for(var i=0;i<nums.length-1;i++){
                for(var j=0;j<nums.length-1-i;j++){
                    if(nums[j]>nums[j+1]){
                        var tmp=nums[j+1];
                        nums[j+1]=nums[j];
                        nums[j]=tmp;
                    }
                }
            
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值