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);