15.4折半查找(二分查找):仅仅适用于顺序表

发布时间:2024年01月16日

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

typedef int ElemType;
typedef struct {
    ElemType *ele;
    int length;
} Table;

void initTable(Table &table, int length) {
    table.ele = (ElemType *) malloc(sizeof(ElemType) * length);
    table.length = length;
    srand(time(NULL));
    for (int i = 0; i < table.length; i++) {
        table.ele[i] = rand() % 100;
    }
}

void printTable(Table table) {
    for (int i = 0; i < table.length; i++) {
        printf("%3d", table.ele[i]);
    }
}

int binarySearch(Table table, int key) {
    int low = 0;
    int hight = table.length - 1;
    int midle;
    while (low <= hight) {
        midle = (hight + low) / 2;
        if (key > table.ele[midle]) {
            low = midle + 1;
        } else if (key < table.ele[midle]) {
            hight = midle - 1;
        } else {
            return midle;
        }
    }
    return -1;
}

int compare(const void *left, const void *right) {
    return *(int *) left - *(int *) right;
}

int main() {
    Table table;
    int key;//需要查找元素
    initTable(table, 10);
    qsort(table.ele, table.length, sizeof(ElemType), compare);//排序
    printTable(table);
    scanf("%d", &key);
    int pos = binarySearch(table, key);
    if (pos) printf("%d", pos);
    return 0;
}

文章来源:https://blog.csdn.net/qq_45827004/article/details/135621550
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。