编辑代码

#include <iostream>
#include <malloc.h>
    using namespace std;
    typedef int KeyType;
    typedef int InfoType;
    typedef struct {
        KeyType key;//关键字域
//        InfoType otherinfo;
    }ElemType;
    typedef struct {
        ElemType* elem;
        int length;
    }SSTable;
    int  Search_Bin(SSTable ST, KeyType key)
    {
        int low, high, mid;
        low = 1;
        high = ST.length;
 
        while (low <= high)
        {
            mid = (low + high) / 2;			//找到中间位置
            if (key == ST.elem[mid].key)
            {
                return mid;					//如果等于查找的记录则返回
            }
            else if (key < ST.elem[mid].key)
            {
                high = mid - 1;				//如果大于查找的记录则重新定位high指针
            }
            else
            {
                low = mid + 1;				//如果小于查找的记录则重新定位mid指针
            }
        }
 
        return 0;
    }
    int main() {
        SSTable ST;
        cout << "请输入元素个数:";
        cin >> ST.length;
        ST.elem = (ElemType*)malloc(sizeof(ElemType));
        cout << "请依次输入元素:";
        for (int i = 1; i <= ST.length; i++) {
            cin >> ST.elem[i].key;
        }
        int f;
        while (1) {
            cout << "请输入要查找的元素:";
            cin >> f;
            if (Search_Bin(ST, f) == 0) {
                cout << "未找到该元素!" << endl;
            }
            else {
                cout << "该元素在第" << Search_Bin(ST, f) << "位" << endl;
            }
        }
    }