#include <iostream>
#include <string>
using namespace std;
const int MAXSIZE = 100;
typedef char KeyType;
typedef struct
{
KeyType key;
} DataType;
typedef struct
{
DataType list[MAXSIZE];
int length;
}SSTable;
//顺序表查找1
int SeqSearch(SSTable S, DataType x)
{
int i = 0;
while(i < S.length && S.list[i].key != x.key)
i++;
if(S.list[i].key == x.key)
return i + 1;
else
return 0;
}
//哨兵项的静态查找
int SeqSearch2(SSTable S, DataType x)
{
int i = S.length;
S.list[0].key = x.key;
while(S.list[i].key != x.key)
{
i--;
}
return i;
}
//有序折半查找
int BinarySearch(SSTable S, DataType x)
{
int low, high, mid;
low = 0;high = S.length;
while(low < high)
{
mid = (high + low) / 2;
if(S.list[mid].key == x.key)
return mid + 1;
else if(S.list[mid].key < x.key)
{
low = mid + 1;
}
else high = mid - 1;
}
return 0;
}
int main()
{
SSTable S1 = { {'1','2','3','4','5','6','7','8','9','a','c','d','v','b'},14 };
SSTable S2 = { { '0','1','2','3','4','5','6','7','8','9'},10 };
DataType x = { '5'};
int a, b, c, d;
a = SeqSearch(S1, x);
cout << "顺序查找:" << a << " " << x.key << endl;
b = SeqSearch2(S1, x);
cout << "哨兵项查找:" << b << " " << x.key << endl;
c = SeqSearch2(S2, x);
cout << "哨兵项查找:" << c << " " << x.key << endl;
d = BinarySearch(S2, x);
cout << "折半查找:" << d << " " << x.key << endl;
return 0;
}