// Программа иллюстрирует
// эвристический алгоритм поиска
#include < iostream.h>
#include
const int MAX_ELEMS = 10;
const int NOT_FOUND = -1;
class myArray
{
public:
myArray(int flnitVal = 0);
int& operator[](int nlndex)
{ return (m_nArray[n lndex]; }
void show(const char* pszMsg = "",
const int nNumElems = MAX_ELEMS,
const int bOneLine = 1);
int heuristicSearch(int nKey,
int nLast = MAX_ELEMS - 1,
int nFirst = 0);
protected:
int m_nArray[MAX_ELEMS];
};
myArray::myArray(int flnitVal)
{
for (int i = 0; i < MAX_ELEMS; i++)
m_nArray[i] = flnitVal;
}
void myArray: :show(const char* pszMsg,
const int nNumElems,
const int bOneLine)
{
cout << pszMsg;
if (bOneLine) {
for (int i = 0; i < nNurnElems; i++)
cout << m_nArray[i] << ;
cout << end l;
}
else {
for (int i = 0; i < nNumElems; i++)
cout << m_nArray[ i ] " end l;
cout " end l;
}
}
int myArray: :heuristicSearch( int nKey, int nLast, intnFirst)
{
for (int i = nFirst; i <= nLast; i++)
if (m_nArray[i] == nKey)
break;
if (i <= nLast) {
if(i >0) { // перестановка элементов с индексами i и i-1
int nSwap = (m_nArray[ i ];
m_nArray[i] = m_nArray[i-1];
m_nArray[--i] = nSwap;
}
return i;
}
else
return NOT_FOUND;
}
main()
{
int j;
int nLast = MAX_ELEMS - 1;
int nArr[MAX_ELEHS] = { 23, 45, 89. 74, 51, 18, 87, 63, 36, 38 };
myArray Array;
for (int i = 0; i < MAX_ELEMS; i++)
Array[i] = nArr[i];
Array. show("lnitial heuristic array is: ");
for (i = 0; i < MAX_ELEMS / 2; i++) {
cout << "Searching for " << nArr[nLast];
j = Array.heuristicSearch(nArr[nLast]);
if (j != NOT_FOUND)
cout << " found match at index " << j << end l;
else
cout << " found no match\n";
Array.show("Heuristic array is: ");
}
return 0;
}
Вывод программы
Initial heuristic array is: 23 45 89 74 51 18 87 63 36 38
Searching for 38 found match at index 8
Heuristic array is: 23 45 89 74 51 18 87 63 38 36
Searching for 38 found match at index 7
Heuristic array is: 23 45 89 74 51 18 87 38 63 36
Searching for 38 found match at index 6
Heuristic array is: 23 45 89 74 51 18 38 87 63 36
Searching for 38 found match at index 5
Heuristic array is: 23 45 89 74 51 38 18 87 63 36
Searching for 38 found match at index 4
Heuristic array is: 23 45 89 74 38 51 18 87 63 36
Содержание