zoukankan      html  css  js  c++  java
  • 二分查找法c语言实现

    二分查找法是从已经排序的线性表(通常是数组)里快速查找到目标元素所在索引,时间复杂度O(log2n)。

    以下是从java源代码中抄来,稍微修改的代码。

    #include <stdio.h>
    #include <assert.h>
    
    #define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
    
    int binarySearch(const int[], size_t,const int);
    
    void rangeCheck(size_t, size_t, size_t);
    
    int binarySearch0(const int[], size_t fromIndex, size_t toIndex, const int);
    
    int main()
    {
        int array[] = {1, 3, 5, 7, 9};
        int key = 3;
        int result = binarySearch(array, ARRAY_SIZE(array),key);
    
        if( result == -1)
            printf("Element %d is not present in array
    ",key);
        else
            printf("Element %d is present at index %d
    ", 
                                key,result); 
    
        
        return 0;
    }
    
    int binarySearch(const int array[], size_t size,const int key)
    {
        return binarySearch0(array,0, size,key);
    }
    
    void rangeCheck(size_t arrayLength , size_t fromIndex, size_t toIndex)
    {
        assert(fromIndex > toIndex);
        assert(fromIndex < 0);
        assert(toIndex > arrayLength);
    }
    //函数指针()
    int binarySearch0(const int array[], size_t fromIndex, size_t toIndex, const int key)
    {
        int low = fromIndex;
        int high = toIndex - 1;
        while (low <= high) {
            int mid = (low + high) >> 1; //算法精妙之处,用位移方法快速决定中值的索引
            
                int midVal = array[mid];        
                int cmp = midVal - key;
            
            if (cmp < 0)
                low = mid + 1;
            else if (cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
            return -(low + 1);  // key not found.
        return 0;
    }

    运行结果:

    Element 3 is present at index 1
  • 相关阅读:
    面试题准备
    ImageList控件
    修改Visual Studio 2010 帮助文件库的位置
    委托与事件(续)
    PictureBox
    我的廣播情緣12/26
    回首我的2007 12/25
    水晶報表:列印支票金額12/12
    聖誕節快樂
    新年快樂
  • 原文地址:https://www.cnblogs.com/passedbylove/p/11255192.html
Copyright © 2011-2022 走看看