2011年11月27日 星期日

Binary Search 二分搜尋法

#include <stdio.h>

#define SIZE 10
#define TARGET 23

int main(void)
{
    int num[SIZE] = {1, 2, 7, 10, 23, 89, 130, 289, 290, 350};
    int low, mid, high, target;

    target = TARGET;

    low = 0;
    high = SIZE-1;
    while (low <= high)
    {
        mid = (low+high) / 2;
        if (target > num[mid])
            low = mid + 1;
        else if (target < num[mid])
            high = mid - 1;
        else
        {
            printf("%d is at the position %d\n", target, mid);
            break;
        }
    }
    if (low > high)
        printf("%d is not in the sequence\n", target);

    return 0;
}

沒有留言:

張貼留言