2분 검색의 순환 버전과 귀속 버전

이분 검색은 질서정연한 표에서 원소가 존재하는지 찾는 것이다. 시간의 복잡도는 대수 단계이고 많은 문제에서 변체가 있다. 이분 검색의 귀속 버전 실현과 비귀속 버전을 복습해 보자.
코드 및 테스트 함수:
#include 
using namespace std;



//  
int BinaryNorRec(int array[], int size, int key)
{
	int mid = -1;
	int left = 0;
	int right = size - 1;

	while (left <= right)
	{
		mid = (left + right) / 2;
		if (array[mid] == key)
		{
			return mid;
		}
		else if (array[mid] < key)
		{
			left = mid + 1;
		}
		else
		{
			right = mid - 1;
		}
	}
	if (left > right)
		return -1;
}

//  
int BinaryRec(int arr[], int left, int right, int key)
{

	int mid = -1;

	if (left <= right)
	{
		mid = (left + right) / 2;

		if (arr[mid] == key)
			return mid;
		else if (arr[mid] < key)
			return BinaryRec(arr, mid + 1, right, key);
		else
			return BinaryRec(arr, left, mid - 1, key);
	}

	return mid;

}

//  
void TestBinaryRec()
{
	int array[] = { 4, 5, 6, 7, 8, 9, 10, 11 };
	int size = sizeof(array) / sizeof(array[0]);

	cout << "find: 4    " << BinaryRec(array,0, size-1, 4) << endl;
	cout << "find: 5    " << BinaryRec(array,0, size-1, 5) << endl;
	cout << "find: 6    " << BinaryRec(array,0, size-1, 6) << endl;
	cout << "find: 7    " << BinaryRec(array,0, size-1, 7) << endl;
	cout << "find: 8    " << BinaryRec(array,0, size-1, 8) << endl;
	cout << "find: 9    " << BinaryRec(array,0, size-1, 9) << endl;
	cout << "find: 10   " << BinaryRec(array,0, size-1, 10) << endl;
	cout << "find: 11   " << BinaryRec(array,0, size-1, 11) << endl;
	cout << "find: 12   " << BinaryRec(array,0, size-1, 12) << endl;
	cout << "find: 3    " << BinaryRec(array,0, size-1, 3) << endl;
	cout << "find: -1   " << BinaryRec(array,0, size-1, -1) << endl;
	//find: 4    0
	//find: 5    1
	//find: 6    2
	//find: 7    3
	//find: 8    4
	//find: 9    5
	//find: 10   6
	//find: 11   7
	//find: 12   -1
	//find: 3    -1
	//find: -1   -1
}
//  
void TestBinarySearch()
{
	int array[] = { 4, 5, 6, 7, 8, 8, 9, 10, 11 };
	int size = sizeof(array) / sizeof(array[0]);

	cout << "find: 4    " << BinaryNorRec(array, size, 4) << endl;
	cout << "find: 5    " << BinaryNorRec(array, size, 5) << endl;
	cout << "find: 6    " << BinaryNorRec(array, size, 6) << endl;
	cout << "find: 7    " << BinaryNorRec(array, size, 7) << endl;
	cout << "find: 8    " << BinaryNorRec(array, size, 8) << endl;
	cout << "find: 9    " << BinaryNorRec(array, size, 9) << endl;
	cout << "find: 10   " << BinaryNorRec(array, size, 10) << endl;
	cout << "find: 11   " << BinaryNorRec(array, size, 11) << endl;
	cout << "find: 12   " << BinaryNorRec(array, size, 12) << endl;
	cout << "find: 3    " << BinaryNorRec(array, size, 3) << endl;
	cout << "find: -1   " << BinaryNorRec(array, size, -1) << endl;
	//  
	//find: 4    0
	//find: 5    1
	//find: 6    2
	//find: 7    3
	//find: 8    4
	//find: 9    5
	//find: 10   6
	//find: 11   7
	//find: 12   -1
	//find: 3    -1
	//find: -1   -1
}

int main()
{
	
	TestBinarySearch();
	cout << endl; //  
	TestBinaryRec();
	return 0;
}

좋은 웹페이지 즐겨찾기