码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找 binary search

时间:2014-09-18 11:30:13      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:数据结构   二分查找   

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;
}

bubuko.com,布布扣






bubuko.com,布布扣





二分查找 binary search

标签:数据结构   二分查找   

原文地址:http://blog.csdn.net/cinmyheart/article/details/39368957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!