This article mainly introduces the example code of JavaScript using binary method to find data. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
Organize the documents and search out an example code of JavaScript using binary method to find data. Take a note by the way
//二分法查数据 var arr=[41,43,45,53,44,95,23]; var b=44; var min=0; var max=arr.length; for(var i=1;i<arr.length;i++){ //外层循环控制排序的次数 for(var j=0;j<arr.length-i;j++){//内层循环控制循环的个数 if(arr[j]<arr[j+1]){ z=arr[j]; arr[j]=arr[j+1]; arr[j+1]=z; } } } // alert(arr[3]) while(true){ //二分查数就是先把一组数据按顺序排好后,从中间将这一组数据一分为二,看想要查得数在哪个范围内,然后再一分为二,直到找 /* for(var i=0;i<arr.length;i++)*/ //这么写不对? 这个数为止 var zjs=parseInt((min+max)/2); //因为(min+max)/2有可能为小数,所以加上一个整数强制转换 if(zjs==min){ 当要查找数的数组为一个偶数个数的数组的时候最后剩下的数的个数为2的时候,需要加个条件再给判断一下 if(b=arr[zjs+1]){ alert(zjs+1); break; } } if(b==arr[zjs]){ alert(zjs) break;} else if(b>arr[zjs]){ min=zjs; } else{max=zjs}}
Find the total score of 10 scores, the highest score, the lowest score
var arr = new Array(80,70,86,58,90,35,89,67,50,100); var sum = 0; var maxd = 0; var mind = 100; //想要查最小数最好用满分最大数做可以比较的基数 for(var i=0;i<arr.length;i++){ sum = sum +arr[i]; if(arr[i]>maxd){ maxd = arr[i]; } if(arr[i]<mind){ mind = arr[i]; } } alert(sum); alert(maxd); alert(mind);
Add a unique number to the array
//var a=7; var a=parseInt(prompt("请输入一个数")); var x=0; var arr=[1,2,3,4,5] for(var i=0;i<arr.length;i++){ if(a==arr[i]){ x=1; break;}} if(x==0){ arr.push(a)} alert(arr.length)
I have never been exposed to similar questions before using binary search data. I can’t think of any ideas. After the teacher finished speaking, I still seemed to understand but I didn’t understand until I typed it out. Bubble sorting It looks quite easy, but when it comes to typing the code yourself, you make mistakes again. You can't always compare the gourds to the gourds, you should have your own understanding of why you type like this, and type more code to avoid similar mistakes in the future. Small mistakes, the variables you define must be remembered, and they echo before and after. When you can't define it, use one, and when you use it, use another one. Remember to add semicolons and curly braces.
The above is the detailed content of An introduction to how JavaScript uses the binary method to find data. For more information, please follow other related articles on the PHP Chinese website!