首页 > 其他 > 详细

二分法查找

时间:2015-10-01 12:49:16      阅读:199      评论:0      收藏:0      [点我收藏+]
 1 var arr = [1, 2, 3, 4, 5, 6, 7, 8];
 2 var a = 1;
 3 var start = 0;
 4 var end = arr.length - 1;
 5 
 6 // 二分法递归方法
 7 function find(arr, a, start, end) {
 8     var temp = Math.ceil((end + start) / 2);
 9     if (start > end) {
10         console.log(‘找不到‘);
11         return false;
12     }
13     if (arr[temp] == a) {
14         console.log("找到了");
15         return true;
16     } else if (arr[temp] > a) {
17         end = temp - 1;
18         find(arr, a, start, end);
19     }
20     else if (arr[temp] < a) {
21         start = temp + 1;
22         find(arr, a, start, end);
23     }
24 }
25 
26 // 二分法非递归
27 function find2(arr, a, start, end) {
28     while ((end - start) >= 0) {
29         var temp = Math.floor((end + start) / 2);
30         console.log(temp)
31         if (arr[temp] == a) {
32             console.log(‘找到了‘);
33             return true;
34         } else if (arr[temp] > a) {
35             end = temp - 1;
36         } else if (arr[temp] < a) {
37             start = temp + 1;
38         }
39     }
40     console.log(‘找不到‘);
41     return;
42 }
43 
44 find(arr, a, start, end);
45 find2(arr, a, start, end);

 

二分法查找

原文:http://www.cnblogs.com/gemicat/p/4850865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!