简体   繁体   中英

Iterative binary search with only two comparisons?

Adjust the iterative binary search code so that it uses only two comparisons instead of three (in the main while loop). *Note: The three comparisons are in the while loop, and two if statements within the loop.

#include <stdio.h>

int ItBinarySearch(int arr[], int len, int target) {

    int first = 0;
    int last = len-1;

    while (first <= last){
        // Assert: array is sorted
        int mid = (first+last) / 2;

        if (target == arr[mid])
            return 1;

        if (target < arr[mid])
            last = mid-1;

        else first = mid+1;
    }
    return 0;
}

int main(void){
    int arr[6]={0,1,2,3,4,5};
    int len=sizeof(arr)/sizeof(arr[0]);
    int target = 4;
    printf("%d\n",ItBinarySearch(arr,len,target));
}

Hint: try moving one of the if/else statements outside the loop. Which if/else would be the most likely candidate where the algorithm would still work if it were outside the statement?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM