二分法在有序数组中的应用(Java&C)-在有序数组中确定num是否存在

时间:2024-04-13 07:09:11

Java实现

public static boolean exist(int[] arr, int num) {
		if (arr == null || arr.length == 0) {
			return false;
		}
		int L = 0int 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;
}