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