C++顺序表折半查找

算法思想

折半查找:又称二分查找,适用于有序的顺序表。
   先将中间位置元素与Key进行比较
      若相等,则返回中间位置下标
      若不相等:
       ① key<中间值,在左半边继续查找
       ② key>中间值,在右半边继续查找

算法实现

int BinarySearch(sqList L,int key)
{
	int low=0,high=L.length-1;
	while(low<=high)//'<='很关键
	{
		int mid=(low+high)/2;
		if(L.data[mid]==key)
			return mid+1;
		else if(key<L.data[mid])
			high=mid-1;
		else
			low=mid+1;
	}
	return  -1;
}

运行代码

#include "stdafx.h"
#include<iostream>
using namespace std;
#define MaxSize 50

typedef struct
{
	int data[MaxSize];
	int length;
}sqList;
void Creat(sqList &L);
int Search(sqList L,int key);//顺序查找
int Binary_Search(sqList L,int key);//二分查找
int _tmain(int argc, _TCHAR* argv[])
{
	sqList l;int x;
	Creat(l);
	cout<<"2在第"<<Binary_Search(l,2)<<"个位置。"<<endl;
	cout<<"5在第"<<Binary_Search(l,5)<<"个位置。"<<endl;
	system("pause");
	return 0;
}
void Creat(sqList &L)
{ 
	for(int i=0;i<5;i++)
	{
		L.data[i]=i+1;
	}
	L.length =5;
	for (int i = 0; i < L.length; i++)
	{
		cout<<L.data[i]<<" ";
	}
	cout<<endl<<endl;
}
int Search(sqList L,int key)
{
	for (int i = 0; i < L.length; i++)
	{
		if(L.data[i]==key)
			return i+1;
	}
	return -1;
}
int Binary_Search(sqList L,int key)
{
	int low=0,high=L.length-1;
	while(low<=high)//‘<=’很关键
	{
		int mid=(low+high)/2;
		if(L.data[mid]==key)
			return mid+1;
		else if(key<L.data[mid])
			high=mid-1;
		else
		    low=mid+1;
	}
	return -1;
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值