源码+注释
#include <malloc.h>
#include <stdio.h>
#define MAXSIZE 2147483647
#define OK 1
#define ERROR 0
typedef struct {
int key;
int otherInfo;
} ElemType;
typedef struct {
ElemType *elem;
int length;
} SqSTable;
int InitTable(SqSTable *table);
int CreateTable(SqSTable *table, int length);
int SearchBin(SqSTable table, int key);
int main() {
SqSTable table;
if (!(InitTable(&table))) {
printf("空间申请失败!!!");
}
CreateTable(&table, 122222);
printf("二分查找结果:%s \n", SearchBin(table, 333) == 0 ? "没有找到" : "找到了");
getchar();
}
int InitTable(SqSTable *table) {
table->elem = (ElemType *) malloc(sizeof(SqSTable) * MAXSIZE);
if (table->elem == NULL) {
return ERROR;
}
table->length = 0;
return OK;
}
int CreateTable(SqSTable *table, int length) {
if (table->length != 0) {
return ERROR;
}
for (int i = 1; i <= length; i++) {
table->elem[i].key = i;
table->length++;
}
return OK;
}
int SearchBin(SqSTable table, int key) {
int leftIndex = 1;
int rightIndex = table.length;
while (leftIndex <= rightIndex) {
int minIndex = (leftIndex + rightIndex) / 2;
if (key == table.elem[minIndex].key) {
return minIndex;
} else if (key < table.elem[minIndex].key) {
rightIndex = minIndex - 1;
} else {
leftIndex = minIndex + 1;
}
}
return 0;
}