-
Notifications
You must be signed in to change notification settings - Fork 274
/
bisearch.c
53 lines (37 loc) · 984 Bytes
/
bisearch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// bisearch.c
// Algorithms - Binary search
//
// Created by YourtionGuo on 11/05/2017.
// Copyright © 2017 Yourtion. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "search.h"
#pragma mark - Public
int bisearch(void *sorted, const void *target, int size, int esize,
int(*compare)(const void *key1, const void *key2))
{
int left, middle, right;
/// 持续执行搜索,直到 left 和 right 相交
left = 0;
right = size - 1;
while (left <= right) {
middle = (left + right) / 2;
switch (compare(((char *)sorted + (esize * middle)), target)) {
case -1:
/// 准备向中间元素右方执行搜索
left = middle + 1;
break;
case 1:
/// 准备向中间元素左方执行搜索
right = middle - 1;
break;
case 0:
/// 将找到的元素索引返回
return middle;
}
}
/// 没找到元素返回 -1
return -1;
}