JavaScriptを使って二分検索(再帰)を実現します.

2608 ワード

<html>
<head>
   <title>    title>
   <script language="javascript" type="text/javascript">
   var arr=[1,4,6,8,9,90,800];
   function binarySearch(arr,findVal,leftIndex,rightIndex)
   {
        if(leftIndex>rightIndex){
            document.writeln("   !!!");
            return;
        }

        var midIndex=Math.floor((leftIndex+rightIndex)/2);
        var midVal=arr[midIndex];

        if(midVal>findVal){
            binarySearch(arr,findVal,leftIndex,midIndex-1);
        }else if(midVal1,rightIndex);
        }else{
            document.writeln("   !   :"+midIndex);
            return;
        }
   }

   binarySearch(arr,2,0,arr.length-1);
   script>
head>
<body>body>
html>