두 갈래 찾기

3032 단어 csearch
다음은 두 갈래 로 이전 요소 와 마지막 요 소 를 되 돌려 주 는 아래 표 시 를 찾 습 니 다.
/* * Copyright (c) 2011 alexingcool. All Rights Reserved. */ #include using namespace std; int array[] = {2, 2, 2, 2, 2}; const int size = sizeof array / sizeof *array; int BinarySearchAtFirst(int (&array)[size], int left, int right, int dest) { while(left < right) { int mid = left + (right - left) / 2; if(array[mid] >= dest) right = mid; else left = mid + 1; } if(array[left] == dest) return left; else return -1; } int BinarySearchAtLast(int (&array)[size], int left, int right, int dest) { while(left < right) { int mid = left + (right - left + 1) / 2; if(array[mid] <= dest) left = mid; else right = mid - 1; } if(array[left] == dest) return left; else return -1; } void main() { cout << "enter a number to search" << endl; int dest; cin >> dest; int pos = BinarySearchAtLast(array, 0, size - 1, dest); if(pos != -1) cout << "find it at: " << pos << endl; else cout << "can't find it" << endl; }
상기 코드 에 문제 가 있 는 것 같 습 니 다.
#include <iostream>

using namespace std;

int array[] = {1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4};
const int size = sizeof array / sizeof *array;

int binarySearchLeft(const int (&array)[size], int value)
{
	int left = 0;
	int right = size - 1;

	while (left < right)
	{
		int mid = left + (right - left) / 2;

		if (array[mid] >= value)
			right = mid;
		else
			left = mid + 1;
	}

	if (array[left] == value)
		return left;
	else
		return -1;
}

int binarySearchRight(const int (&array)[size], int value)
{
	int left = 0;
	int right = size - 1;

	while (left < right)
	{
		int mid = left + (right - left + 1) / 2;

		if (array[mid] > value)
			right = mid - 1;
		else
			left = mid;
	}

	if (array[left] == value)
		return left;
	else
		return -1;
}

int main()
{
	int left = binarySearchLeft(array, 2);
	cout << "left: " << left << endl;
	int right = binarySearchRight(array, 2);	
	cout << "right: " << right << endl;
}

2 분 동안 찾 은 변종:
int binarySearchLeft(int *array, int size, int value)
{
	if (array == NULL || size <= 0)
		return -1;

	int left = 0;
	int right = size - 1;

	while (left != right - 1 && left < right)
	{
		int mid = left + (right - left) / 2;

		if (array[mid] > value)
		{
			right = mid;
		}
		else
		if (array[mid] < value)
		{
			left = mid;
		}
		else
		{
			return mid;
		}
	}

	return left;
}

int binarySearchRight(int *array, int size, int value)
{
	if (array == NULL || size <= 0)
		return -1;

	int left = 0;
	int right = size - 1;

	while (left != right - 1 && left < right)
	{
		int mid = left + (right - left) / 2;

		if (array[mid] > value)
		{
			right = mid;
		}
		else
			if (array[mid] < value)
			{
				left = mid;
			}
			else
			{
				return mid;
			}
	}

	return right;
}

좋은 웹페이지 즐겨찾기