⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 b_5_1.cpp

📁 C++应用教程原码,里面包含该书中有十三章内容的代码,详细具体
💻 CPP
字号:
#include "stdafx.h"
#include "iostream"
using namespace std;

int search(int *list,int &key,int len)
{
	int *first,*end,*mid;
	first=list;
	end=list+len-1;
	while(first<=end)
	{
		mid=first+(end-first)/2;   // 计算出中间位置
		if(*mid < key)             // 将key值与中间位置的值比较
			first=mid+1;           // 新的查找范围在后半部
		else if(*mid > key)
			end=mid-1;             // 新的查找范围在前半部
		else 
		 return (mid-list+1);      //找到了key所在的位置
	}
		return -1;    // 在数组中没有找到和key值相同的元素
}
void main()
{
	int list[10] = {12,34,55,62,68,76,79,88,91,97};	
	int key,position=-1;
    int (*s)(int *,int &,int)=search;
	for (int i=0;i<10;i++)
		cout<<*(list+i)<<" ";
	cout<<endl;

	cout<<"请输入要查阅的字符串:";
	cin>>key;

    position = (*s)(list,key,10);
	if (position != -1) 
		cout<<"恭喜!要找的数字是数组的第"<<position<<"个元素。"<<endl;
	else
	    cout<<"报歉!你要找的数字不在该数组中!"<<endl;
	 cin.get(); cin.get(); //等待结束,以便调测程序,可以删除
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -