顺序查找, 又叫"线性查找", 通常用于线性表(顺序存储, 链式存储)
算法思想: 从头到尾, 从尾到头.
顺序查找实现方式一(从头到尾)
typedef struct { // 查找表的数据结构(顺序表)
ElemType *elem; // 动态数组基址
int tableLen; // 表的长度
}SSTable;
int search_seq(SSTable st, ElemType key) {
int i;
for(i=0; i<st.tableLen && st.elem[i] != key; i++);
return i==st.tableLen? -1 : i;
}
顺序查找实现方式二(哨兵, 从尾到头)
typedef struct { // 查找表的数据结构(顺序表)
ElemType *elem; // 动态数组基址
int tableLen; // 表的长度
}SSTable;
int search_seq(SSTable st, ElemType key)
{
st.elem[0] = key; // 把0号位置给目标值, 哨兵
int i;
for(i=st.tableLen; st.elem[i] != key; --i);
return i;
}