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

#include 
#include 

#include 
#include 

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;
}

折半查找---------c++_第1张图片 

你可能感兴趣的:(python,pandas,开发语言)