Binary search

Binary Search




Jon Bentley曾经说过类似的话:“90%的程序员无法正确实现二分查找算法



就冲着这句话去写binary search


binary_search 的算法实现部分

/*********************************************************
code writer	:	EOF
code file	:	binary_search.c
code date	:	2014.9.18
e-mail		:	jasonleaster@gmail.com

description:
	You may have to KNOW that the @array was
sequenced from min to max  when you use "binary search".

	If this function find the element , return the
location in the @array, otherwise return -1.

********************************************************/
#include <stdio.h>

int binary_search(int* array,int size,int element)
{
	if(!array)
	{
		printf("You passed NULL into function: %s()\n",__FUNCTION__);
		return -1;
	}

	int low = 0;
	int mid = 0;
	int high= 0;

	for(low = 0,high = size-1;low <= high;)
	{
		mid = (low+high)/2;
		
		if(array[mid] < element)
		{
			low = mid+1;
		}
		else if(array[mid] > element)
		{
			high = mid-1;
		}
		else
		{
			/*
			** 	found that.
			*/
			return mid; 
		}
	}

	return -1;
}


测试用程序

#include <stdio.h>
#include "binary_search.h"

int main()
{
	int number[10] = {0,2,6,8,10,15,18,40,99};

	int what_i_want = 18;
	int ret = 0;

	ret = binary_search(number,sizeof(number)/sizeof(number[0]),what_i_want);

	if(ret < 0)
	{
		printf("Not found!\n");
		return 0;
	}

	printf("location:%d number[%d]:%d\n",ret,ret,number[ret]);

	return 0;
}




update:2015.1.8

添加python版本的实现

'''
Code writer : EOF
Code date   : 2015.01.08
Code file   : bs.py
e-mail      : jasonleaster@gmail.com

Code description:
       Here is a implementation for 
how to do binary search in Python.

'''
def binary_search(array, element):

    high = len(array)
    mid = -1
    for low in range(len(array)) :
        mid = (low + high)/2

        if array[mid] < element :
             low  = mid + 1
        elif array[mid] > element :
             high = mid - 1
        else :
             return mid

    return -1
     
def main():
    number = [1,2,3,4,5]

    print number
    print number[binary_search(number,3)]

main()












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值