www.zhblog.net

查看升序数组中是否包含项

bsearch在数组中查找与key匹配的项

数组必须按升序排列

struct point {
int x;
char *name;
};
typedef struct point PT;

int cmpi(void *v, void *o) {
int m = *(int *) v;
int n = *(int *) o;
if (m < n) {
return -1;
} else if (m == n) {
return 0;
} else if (m > n) {
return 1;
}
}

int cmps(void *v, void *o) {
char *m = (char *) v;
char *n = *(char **) o;
return strcmp(m, n);
}

int cmpsti(void *v, void *o) {
PT *m = (PT *) v;
PT *n = (PT *) o;
if (m->x < n->x) {
return -1;
} else if (m->x == n->x) {
return 0;
} else if (m->x > n->x) {
return 1;
}
}

int cmpsts(void *v, void *o) {
PT *m = (PT *) v;
PT *n = (PT *) o;
return strcmp(m->name, n->name);
}

int main() {
// int
int base[] = {3, 5, 8, 12, 54, 67};
int key1 = 8;
void *rp1 = bsearch(&key1, base, sizeof(base) / sizeof(int), sizeof(int),
(int (*)(const void *, const void *)) cmpi);
if (rp1 != NULL) {
printf("%d\n", *(int *) rp1);
}

char *s[] = {"aaa", "bbb", "ccc", "eee"};
char *key2 = "eee";
void *rp2 = bsearch(key2, s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), (int (*)(const void *, const void *)) cmps);
if (rp2 != NULL) {
printf("%s\n", *(char **) rp2);
}

// struct int
PT pts[3] = {{1, "aaa"},
{2, "bbb"},
{3, "ccc"}};
PT key3 = {2, "bbb"};
void *rp3 = bsearch(&key3, pts, sizeof(pts) / sizeof(pts[0]), sizeof(pts[0]),
(int (*)(const void *, const void *)) cmpsti);
if (rp3 != NULL) {
printf("%d - %s\n", ((PT *) rp3)->x, ((PT *) rp3)->name);
}

// struct char *
PT ptc[3] = {{1, "aaa"},
{2, "bbb"},
{3, "ccc"}};
PT key4 = {2, "bbb"};
void *rp4 = bsearch(&key4, ptc, sizeof(ptc) / sizeof(ptc[0]), sizeof(ptc[0]),
(int (*)(const void *, const void *)) cmpsts);
if (rp4 != NULL) {
printf("%d - %s\n", ((PT *) rp4)->x, ((PT *) rp4)->name);
}
}

 

 

 

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情