include stdafx include iostream include fstream include string include

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#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";
}