折半查找---------c++

#include <iostream>
#include <stdio.h>

#include <stdlib.h>
#include <time.h>

typedef int Element;
typedef struct {//定义结构体类型
    Element *element;//元素指针
    Element Tablen;//元素下标
} STable;


void ST_printf(STable table) {
    for (int j = 1; j < table.Tablen; j++) { ;
        printf("%3d", table.element[j]);
    }
}

void ST_init(STable &table, int i) {
    table.Tablen = i + 1;//本次采用的是哨兵模式。所以多加一个元素作为哨兵的存在位置

    table.element = (Element *) malloc(sizeof(Element) * table.Tablen);

    // srand(time(NULL));
    for (int j = 1; j < table.Tablen; j++) {
        int num = j;
        table.element[j] = ++num;
    }//随机生成数据存入
}

int Table_search(STable table, Element key) {
    table.element[0] = key;
    int i;
    for (i = table.Tablen - 1; table.element[i] != key; i--);

    return i;

}


int Binary_search(STable table, Element x) {
    int low = 0;
    int high = table.Tablen - 1;
    int mid;
   // printf("---");
    while (low <= high) {
        mid = (low + high) / 2;
        if (x > table.element[mid]) {
            low = mid + 1;
         //   printf("---");
        } else if (x < table.element[mid]) {
            high = mid - 1;
           // printf("---");
        } else {
            return mid;
            printf("---");
        }

    }
    return -1;
}
int compare(const  void  *left,const void  *right){
    return *(Element*)right -*(Element*)left;
}
int main() {
    STable sTable;
    ST_init(sTable, 10);
    ST_printf(sTable);
    qsort(sTable.element,sTable.Tablen,sizeof (Element),compare);
    printf("please into your nums---\n");
    Element x;
    scanf("%d", &x);
    int i;
    i = Binary_search(sTable, x);
    printf("%d", i);


    //  Element element = 110;
    //  printf("%d",Table_search(sTable, element));

    //
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值