对分查找

//BinarySearch.h
#ifndef BINARYSEARCH_H
#define BINARYSEARCH_H 

#define NotFound -1

#include <stdio.h>

int  BinarySearch(int *, int , int );

#endif

//BinarySearch.c

#include "BinarySearch.h"

int BinarySearch(int array[], int x, int size)
{
	int low = 0;
	int high = size - 1;
	int mid;

	while(low <= high)
	{
		mid = (low + high)/2;

		if (array[mid] < x)
		{
			low = mid + 1;
		}
		else if (array[mid] > x)
		{
			high = mid - 1;
		}
		else
			return mid;
	}
	
	return NotFound;
}

//main.c

#include "BinarySearch.h"

int main(void)
{
	int array[] = {1,2,3,4,5,6,7,8,9,10,11};
	int size = sizeof(array)/sizeof(*array);
	int x = 5;

	int index = BinarySearch(array, x, size);

	printf("the index is %d\n",index);
	
	return 0;
}
//前提是升序
思路:折半比较,array[mid]小于x说明在mid的右侧,将下限置mid+1,array[mid]大于x说明在mid的左侧,将上限置mid-1;其中的现在条件就是low<=high.

你可能感兴趣的:(对分查找)