递归

    1. function binary_search(arr, low, high, key) {
    2. if (low > high) {
    3. return -1;
    4. }
    5. var mid = parseInt((high+low) / 2);
    6. if (arr[mid] == key) {
    7. return mid;
    8. } else if (arr[mid] > key) {
    9. high = mid - 1;
    10. return binary_search(arr, low, high, key);
    11. } else if (arr[mid] < key) {
    12. low = mid 1;
    13. return binary_search(arr, low, high, key);
    14. }
    15. }

    非递归

    1. function binary_search(arr, key) {
    2. var low = 0;
    3. var high = arr.length - 1;//定义变量为数组两端的下标
    4. while(low <= high) {
    5. var mid = parseInt((high + low) /2);//步骤1
    6. if(key == arr[mid]) {
    7. return mid;//步骤2
    8. } else if(key > arr[mid]) {
    9. low = mid + 1;//步骤3
    10. } else {
    11. high = mid -1;//步骤4
    12. }
    13. }
    14. return -1//步骤6
    15. }