二分法

查找等於某個數的位置

// 查找等於某個數的位置
int binarySearch1(int *nums, int length, int value){
	int low = 0;
	int high = length - 1;
	while (low < high){
		int mid = (low + high) / 2;
		if (nums[mid] < value)
			low = mid + 1;
		else if (nums[mid]>value)
			high = mid - 1;
		else
			return mid;
	}
	if (nums[low] == value)
		return low;
	return -1;
}
複製代碼

查找第一個大於某個數的位置

  直接上代碼:測試

// 查找第一個大於某個數的位置
int binarySearch2(int *nums, int length, int value){
	int low = 0;
	int high = length - 1;
	while (low < high){
		int mid = (low + high) / 2;
		if (nums[mid] <= value)
			low = mid + 1;
		else
			high = mid;
	}
	// 結束時low和high必定相等,而且位置合法
	if (nums[low]>value)
		return low;
	return -1;
}
複製代碼

查找最後一個小於某個數的位置

  和第一種狀況同樣,但要注意避免死循環問題。ui

// 查找最後一個小於某個數的位置
int binarySearch3(int *nums, int length, int value){
	int low = 0;
	int high = length - 1;
	while (low < high){
		int mid = (low + high) / 2;
		if (nums[mid] >= value)
			high = mid - 1;
		else {
			// 若是low==mid,那麼將進入死循環,這是由於此時low+1==high
			if (low == mid){
				if (nums[high] < value)
					low = high;
				break;
			}
			low = mid;
		}
	}
	if (nums[low] < value)
		return low;
	return -1;
}
複製代碼

測試用例

int main(){
	int nums[] = { 1, 2, 3, 4, 5 };
	printf("%d", binarySearch1(nums, 5, 1));
	printf("%d", binarySearch1(nums, 5, 2));
	printf("%d", binarySearch1(nums, 5, 3));
	printf("%d", binarySearch1(nums, 5, 4));
	printf("%d", binarySearch1(nums, 5, 5));
	printf("\n");
	printf("%d", binarySearch2(nums, 5, 1));
	printf("%d", binarySearch2(nums, 5, 2));
	printf("%d", binarySearch2(nums, 5, 3));
	printf("%d", binarySearch2(nums, 5, 4));
	printf("%d", binarySearch2(nums, 5, 5));
	printf("\n");
	printf("%d", binarySearch3(nums, 5, 1));
	printf("%d", binarySearch3(nums, 5, 2));
	printf("%d", binarySearch3(nums, 5, 3));
	printf("%d", binarySearch3(nums, 5, 4));
	printf("%d", binarySearch3(nums, 5, 5));
	return 0;
}
複製代碼
相關文章
相關標籤/搜索