#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
void bin(string, string*);
void perebor(string, string*);
#define n 15
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_CTYPE, "rus");
string arr[n];
string buff;
ifstream file1("sorted_list.txt");
int set;
for (int i = 0; i < n; i++)
file1 >> arr[i];
file1.close();
cout << "Выберите метод поиска:\n" << "1. Перебор\n" << "2. Бинарный\n";
cin >> set;
ifstream test("test.txt");
switch (set)
{
case 1:
while (!test.eof())
{
test >> buff;
perebor(buff, arr);
}
case 2:
while (!test.eof())
{
test >> buff;
bin(buff, arr);
}
}
test.close();
_getch();
return 0;
}
void bin(string strPoiska, string* masPoiska)
{
int imin = 0, imax = n - 1, imid, cnt = 0;
bool found = false;
for (int i = 0; i < n; i++)
{
imid = (imin + imax) / 2;
if (strPoiska < masPoiska[imid])
imax = imid;
else if (strPoiska > masPoiska[imid])
imin = imid;
else if (strPoiska == masPoiska[imid])
{
found = true;
break;
}
cnt++;
}
if (found)
cout << "Строка " << strPoiska << " найдена в позиции "
<< imid + 1 << ". Количество сравнений " << cnt << "\n";
else
cout << "Строка " << strPoiska << " не найдена. Количество сравнений "
<< cnt << "\n";
}
void perebor(string s, string* mas)
{
int i = 0, cnt = 0;
while (i < n)
{
if (s == mas[i]) break;
i++;
cnt++;
}
if (i > n - 1)
cout << "Строка " << s << " не найдена. Количество сравнений "
<< cnt << "\n";
else
cout << "Строка " << s << " Найдена в позиции "
<< i + 1 << ". Количество сравнений " << cnt + 1 << "\n";
}