数组有序的情况下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> //顺序必须有序 var num = 100000; var randomNum = Math.ceil(Math.random()*num); document.title = randomNum; var arr = []; for(var i = 0 ;i<num;i++) { arr.push(i) } console.log(randomNum); //======第一种方式========= function show1(arr,randomNum) { console.time(2) for (var i = 0; i <arr.length; i++) { if(arr[i] === randomNum) { console.timeEnd(2); return arr[i]; } } } show1(arr,randomNum); //======第二种方式========= function show(arr,randomNum) { console.time(1) var first = 0; var last = arr.length -1; while(first <= last) { var mindex = Math.floor((first + last)/2); if(randomNum < arr[mindex]) //大于中间值 { last = mindex -1; }else if(randomNum > arr[mindex]){ first = mindex +1; }else{ console.timeEnd(1) return arr[mindex]; } } } console.log(show(arr,randomNum)); </script> </body> </html>
数组无序的情况下:
使用二分 先把数组排列成有序------然后二分 所花的时间比 普通for循环的时间要长
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> //顺序必须有序 var num = 100000; var randomNum = Math.ceil(Math.random()*num); document.title = randomNum; var arr = []; for(var i = 0 ;i<num;i++) { arr.push(i) } //无序的排序 arr.sort(function(){ return Math.random() -0.5; }) console.log(randomNum); //======第一种方式========= function show1(arr,randomNum) { console.time(2) for (var i = 0; i <arr.length; i++) { if(arr[i] === randomNum) { console.timeEnd(2); return arr[i]; } } } show1(arr,randomNum); //======第二种方式========= function show(arr,randomNum) { console.time(1) arr.sort(function(n1,n2){ return n1 -n2; }) var first = 0; var last = arr.length -1; while(first <= last) { var mindex = Math.floor((first + last)/2); if(randomNum < arr[mindex]) //大于中间值 { last = mindex -1; }else if(randomNum > arr[mindex]){ first = mindex +1; }else{ console.timeEnd(1) return arr[mindex]; } } } console.log(show(arr,randomNum)); </script> </body> </html>