在关键字有序序列中采用二分查找法查找关键字为给定值k的元素,输出查找结果。 要求:有序序列和给定值k都从键盘输入。

在这里插入图片描述

#include "stdio.h"
#include<iostream>//蓝多多算法实验七
#define MAX 100
using namespace std;
int Binary_Search(const int *array, int n, int key)
{
    int low = 1;
    int high = n;
    int mid;
    while(low <= high)
    {
        if (array[0] < array[1])
        {
            mid = (low + high) / 2;
            if (key < array[mid])
                high = mid - 1;
            else if (key > array[mid])
                low = mid + 1;
            else
                return  mid;
        }
        if (array[0] > array[1])
        {
            mid = (low + high) / 2;
            if (key> array[mid])
                high = mid - 1;
            else if (key< array[mid])
                low = mid + 1;
            else
                return  mid;
        }
    }
    return 0;
}
int main()
    {
    int MAXSIZE;
    int key;
    cout<<"please input the size of the array: ";
    cin>>MAXSIZE;
    int num [MAX];
    cout<<"please input a sorted sequence:本程序仅可实现有序序列的查找(即递增或递减)";
    for(int i = 0;i < MAXSIZE;i++)
    {
        cin>>num [i];
    }
    cout<<'\n'<<"please input the key = ";
    cin>>key;
    cout<<endl;
    int key_find = Binary_Search(num ,MAXSIZE,key);
    if(key_find == 0)
        cout<<"NOT FOUND!";
    else
        cout<<"The "<<key<<" is in the "<< key_find + 1 <<" of the sequence!";
    system("pause");
    return 0;
    }

运行结果:略

猜你喜欢

转载自blog.csdn.net/qq_43554335/article/details/106836112
今日推荐