zoukankan      html  css  js  c++  java
  • 二分法查找

    二分法查找,也称折半查找,是一种在有序数组中查找特定元素的搜索算法。查找过程可以分为以下步骤:
    (1)首先,从有序数组的中间的元素开始搜索,如果该元素正好是目标元素(即要查找的元素),则搜索过程结束,否则进行下一步。
    (2)如果目标元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半区域查找,然后重复第一步的操作。
    (3)如果某一步数组为空,则表示找不到目标元素。

    <!DOCTYPE html>
    <html>
      <head>
        <title>demo</title>
        <style type="text/css">
        </style>
        <script type="text/javascript">
        
          function binarySearch(arr,start,end,num){
              
              if(start>=end){
                  alert("查找有误!");
              }
              //排序--必须为有序数组
              arr.sort(function(n1,n2){
                  return n1-n2;
              });
              
              //最后只有两个值得情况
            if(end - start == 1){
                
              if(arr[start] == num){
                return start;
              }else if(arr[end] == num){
                return end;
              }else{
                  return -1;
              }
              
             //其他
            }else{
                
                //中间值的索引
                var center = Math.floor((start + end)/2);
            
                if(num != arr[center]) {//不在中间位置
                  return num > arr[center] ? binarySearch(arr, center, end, num) : binarySearch(arr, start, center, num);
                }else{//正好在中间位置
                    return center;
                }
                
            }
            
          }
          var arr = [12,45,13,10,8,2,20,4,56,25];
          var num1=binarySearch(arr,0,arr.length, 10);
          var num2=binarySearch(arr,0,arr.length, 0);
          console.log(num1);
          console.log(num2);
          
        </script>
      </head>
      <body>
      </body>
    </html>
  • 相关阅读:
    HDU 3547 DIY Cube
    POJ 2975 Nim
    POJ 1678 I Love this Game!
    POJ 2234 Matches Game
    POJ 3537 Crosses and Crosses
    POJ 3710 Christmas Game
    POJ 1704 Georgia and Bob
    HDU 3923 Invoker
    POJ 2154 Color
    PLM更新自定义CLASS
  • 原文地址:https://www.cnblogs.com/yang0901/p/6774736.html
Copyright © 2011-2022 走看看