1)遞歸 2)非遞歸 ...
1)遞歸
1 function binarySearch(data, dest, start, end){ 2 var end = end || data.length - 1, 3 start = start || 0, 4 m = Math.floor((start + end) / 2); 5 if(data[m] == dest){ 6 return m; 7 } 8 if(dest < data[m]){ 9 return binarySearch(data, dest, 0, m-1); 10 }else{ 11 return binarySearch(data, dest, m+1, end); 12 } 13 return false; 14 } 15 var arr = [-34, 1, 3, 4, 5, 8, 34, 45, 65, 87]; 16 binarySearch(arr,4); 17 //3
2)非遞歸
1 function binarySearch(data, dest){ 2 var h = data.length - 1, 3 l = 0; 4 while(l <= h){ 5 var m = Math.floor((h + l) / 2); 6 if(data[m] == dest){ 7 return m; 8 } 9 if(dest > data[m]){ 10 l = m + 1; 11 }else{ 12 h = m - 1; 13 } 14 } 15 16 return false; 17 } 18 var arr = [-34, 1, 3, 4, 5, 8, 34, 45, 65, 87]; 19 binarySearch(arr,4); 20 //3