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

思想:

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

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

// zfd.cpp : 定义控制台应用程序的入口点。
//
#include"stdafx.h"
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<algorithm>
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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值