静态查找表之有序表查找----折半查找(二分查找)

思想:

二分法查找是指已知有序队列中找出与给定关键字相同的数的具体位置。原理是分别定义三个指针low, high, mid,分别指向待查元素所在范围的下界和上界及区间的中间位置,即 mid=(low+high)/ 2,让关键字与mid所指的数比较,若相等则查找成功并返mid, 若关键字小于mid所指的数则high=mid-1,否则low=mid+1,然后继续循环直到找到或找不到为止。

下面代码是二分法的C++实现:

// zfd.cpp : 定义控制台应用程序的入口点。
//
#include"stdafx.h"
#include
#include
#include
#include
#include
using namespace std;
#define MAXSIZE 10
typedef struct node
{
	int list[MAXSIZE];
	int length;
}List;

int binarySearch(List &demo,int key)
{
	int low = 0;
	int high = demo.length - 1;
	int mid = (high +low) / 2;
	while (low <= high)
	{
		
		cout << mid << endl;
		if (key > demo.list[mid])
			low = mid + 1;
		else if (key < demo.list[mid])
			high = mid - 1;
		else
			return mid+1;
		mid = (high + low) / 2;

	}
	return 0;
}
int main()
{
	List demo;
	int data;
	int a[MAXSIZE] = {1,3,6,12,15,19,25,32,38,87};
	for (int i = 0; i < MAXSIZE; i++)
	{
		demo.list[i] = a[i];
	}
	demo.length = MAXSIZE;
	cout << "please input the search number:" << endl;
	cin >> data;
	int result=binarySearch(demo,data);
	if (result)
		cout << "could find the number in the list,position is " << result << endl;
	else
		cout << "could not find the number in the list" << endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(c++语言,算法与数据结构)