菜鸟到高手之 - Binary Search,half-interval search(二分查找,折半查找)

来源:互联网 发布:win10下装linux双系统 编辑:程序博客网 时间:2024/05/29 13:44

/*************************
Reference:
1. Wikipedia
2. Introduction to algorithms(算法导论)

/**********************

优点: 比较次数少,查找速度快,平均性能好
缺点: 待查表为有序表,插入删除困难
适用: 不经常变动而查找频繁的有序列表

For binary search, the array should be arranged in ascending or descending order. A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

拓展:    1. 排序算法    2. 时间复杂度    3. 分治策略

C代码实现方式
一:迭代,采用两个索引值逐渐缩小查找范围
//The binary search algorithm can also be expressed iteratively with two index limits that progressively narrow the search range

int16_t Search_Binary_Iterative(uint32_t *a, uint16_t n, uint32_t *key){    uint16_t low = 0,high = n - 1,mid;    while(low <= high)          // continue searching while [imin,imax] is not empty    {        mid = (low + high)/2;   // calculate the midpoint for roughly equal partition        if(a[mid] == *key)            return mid;         //key found at index imid           //determine which subarray to search        else if(a[mid]< *key)                   low = mid + 1;      // change min index to search upper subarray                     else          {            if(mid >= 1)        // change max index to search lower subarray                high = mid - 1;            else                return -1;        }    }    return -1;                  // key was not found}
0 0