【源代码】C++数据结构算法(十四)静态查找——二分法(折半查找)

日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
运行截图:这里写图片描述
SearchBin.h

#pragma once
#include<iostream>

class List
{
public:
    List(int value[], int n);
    void init(int values[], int n);
    ~List();
    int SearchBin(int key, List&list);
    bool equal(int key, int&k);

private:
    int *elem;
    int length;
    int list_size;
};

SearchBin.cpp

#include<iostream>
#include "SearchBin.h"
using namespace std;



int List::SearchBin(int key,List&list)
{
    int low, high,mid;
    low = 1;
    high = list.length;
    while (low <= high)
    {
        mid = (low + high) / 2;
        if (equal(key,list.elem[mid]))
        {
            return mid;
        }
        if (key<list.elem[mid])
        {
            high = mid - 1;
        }
        else 
        {
            low = mid + 1;
        }
    }
    return -1;
}

bool List::equal(int key, int&k)
{
    return key ==  k;
}


List::List(int values[], int n)
{
    this->init(values,n);
}

List::~List()
{
    delete[]this->elem;
}

void List::init(int values[], int n)
{
    this->list_size = n * 2;
    this->elem = new int[list_size];
    this->length = n;
    for (int i = 0; i < this->length; i++)
    {
        this->elem[i] = values[i];
    }
}

int main()
{
    int n = 15;
    int value[15] = {1,2,3,4,5,6,8,9,10,10,11,12,13,13,14};
    List list(value,15);
    int key;
    cout << "请输入查询的数字:";
    cin >> key;
    cout << key << "为顺序表的第" << list.SearchBin(key,list)+1<< "个元素";
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Handoking/article/details/80268142