Java实现
public static boolean exist(int[] arr, int num) {
if (arr == null || arr.length == 0) {
return false;
}
int L = 0;
int R = arr.length - 1;
int M = 0;
while (L <= R) {
M = (L + R) / 2;
if (arr[M] == num) {
return true;
} else if (arr[M] > num) {
R = M - 1;
} else {
L = M + 1;
}
}
return false;
}
C语言实现
int exist(int arr[], int length, int num) {
if (arr == NULL || length == 0) {
return 0;
}
int L = 0;
int R = length - 1;
int M = 0;
while (L <= R) {
M = (L + R) / 2;
if (arr[M] == num) {
return 1;
}
else if (arr[M] < num) {
L = M + 1;
}
else {
R = M - 1;
}
}
return 0;
}