目录
其实中间还有树跟图的内容的;;;
但是时间不太够,先放着吧;
后面一定补上!!!
顺序查找 & 折半查找(C):
Sqsearch.h:
#ifndef SEARCH_SQSEARCH_H
#define SEARCH_SQSEARCH_H
#define SEQ_TABLE_LEN 11 //设定表长为10,1~10存数据,0用作哨兵
typedef int ElemType;
typedef struct { //一维线性查找表
ElemType *elem; //元素存储空间基地址,0号单元留空
int TabelLen; //表长
}SSTable;
void SeqTable_Init(SSTable *sqtable, ElemType datas[]);
void SeqTable_Print(SSTable sqtable);
int Seq_Search(SSTable ST, ElemType key);
int Binary_Search(SSTable sqtable, ElemType key);
#endif //SEARCH_SQSEARCH_H
Sqsearch.c:
#include "Sqsearch.h"
#include <stdio.h>
#include <stdlib.h>
void SeqTable_Init(SSTable *sqtable, ElemType datas[])
{
ElemType *table_datas = (ElemType*)malloc(sizeof(ElemType)*SEQ_TABLE_LEN);
for (int i = 1; i < SEQ_TABLE_LEN; ++i) {
table_datas[i] = datas[i];
}
sqtable->elem = table_datas;
sqtable->TabelLen = SEQ_TABLE_LEN;
}
void SeqTable_Print(SSTable sqtable)
{
printf("table datas:\n");
for (int i = 1; i < SEQ_TABLE_LEN; ++i) {
printf("---%d---",sqtable.elem[i]);
}
printf("\n");
}
//一维线性表的顺序查找
int Seq_Search(SSTable ST, ElemType key)
{
int i;
ST.elem[0] = key; //0号位置用作哨兵,从后往前查找,从而不必每次都检查数组是否越界
for (i = ST.TabelLen;ST.elem[i] != key; --i); //从后往前找
return i;//若查找失败,返回0
}
//二分查找
int Binary_Search(SSTable L, ElemType key)
{
int low = 0,high = L.TabelLen-1,mid;
while (low <= high) {
mid = (low + high) / 2; //take the middle pos
if(L.elem[mid] == key)
return mid;
else if(L.elem[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; //search fail!
}
主函数测试:
#include <stdio.h>
#include "Sqsearch.h"
int main() {
SSTable sqtable;//sequence search table
ElemType tabel_datas[SEQ_TABLE_LEN] = {0,15,25,45,53,67,235,546,567,855,1234};//假设有序
SeqTable_Init(&sqtable, tabel_datas);//init sqtable
SeqTable_Print(sqtable);
//Sequence Search
int pos1 = 0;
pos1 = Seq_Search(sqtable, 855);//find 855
if(pos1) {
printf("find 855 ok! in positon:%d\n",pos1);
} else {
printf("find 855 error!\n");
}
pos1 = Seq_Search(sqtable, 123);//find 123
if(pos1) {
printf("find 123 ok! in positon:%d\n",pos1);
} else{
printf("find 123 error!\n");
}
//Binary Search
int pos2 = 0;
pos2 = Binary_Search(sqtable, 567);//find 567
if(pos2 != -1) {
printf("find 567 ok! in positon:%d\n",pos2);
} else {
printf("find 567 error!\n");
}
pos2 = Binary_Search(sqtable, 66);//find 66
if(pos2 != -1) {
printf("find 66 ok! in positon:%d\n",pos2);
} else{
printf("find 66 error!\n");
}
return 0;
}
结果:
以上均为个人学习心得,如有错误,请不吝赐教~
THE END