/*
静态表查找:顺序查找,二分查找,斐波那契查找
运行环境:VS2010
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50
typedef struct
{
int key[MAXSIZE + 1]; //0号位置不存值
int length;
}SeqTable;
int F[13] = {0,1,1,2,3,5,8,13,21,34,55,88,143}; //斐波那契数组
SeqTable *CreateSeqTable()
{
int i = 0;
char *ptr = NULL;
SeqTable *st = NULL;
char buf[4*MAXSIZE+1] = "(12,15,27,35,45,52,63,66,73,84,98)"; //测试数据,有序的
st = (SeqTable *)malloc(sizeof(SeqTable));
i = 1;
ptr = buf + 1;
while(1)
{
st->key[i] = atoi(ptr);
ptr = strstr(ptr, ",");
if(!ptr)
{
break;
}
ptr++;
i++;
}
st->length = i;
return st;
}
//顺序查找
//返回: 0 查找失败; 非0 数据在表中的位置
int SequentialSearch(SeqTable *st, int num)
{
int index = 0;
st->key[0] = num;
for(index = st->length; index >= 0; index--)
{
if(st->key[index] == num)
{
break;
}
}
return index;
}
//二分查找
//初始:顺序表必须为有序表
//返回:0 查找失败; 非0 数据在表中的位置
int BinarySearch(SeqTable *st, int num)
{
int mid = 0;
int low = 1;
int high = st->length;
while(low <= high)
{
mid = (low + high) / 2;
if(st->key[mid] == num)
{
return mid;
}
else if(st->key[mid] < num)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return 0;
}
/*
斐波那契查找
初始:顺序表必须为有序表
返回:0 查找失败; 非0 数据在表中的位置
*/
int FibonacciSearch(SeqTable *st, int num)
{
int i = 0;
int k = 0;
int mid = 0;
int low = 1;
int high = st->length;
while(high > F[k] - 1) //计算st->length在Fibonacci
{
k++;
}
for(i = high + 1; i <= F[k] - 1; i++) //将不满的数值填充
{
st->key[i] = st->key[high];
}
while(low <= high)
{
mid = low + (F[k-1] - 1);
if(num < st->key[mid])
{
high = mid - 1;
k = k - 1;
}
else if(num > st->key[mid])
{
low = mid + 1;
k = k - 2;
}
else
{
if(mid <= st->length)
{
return mid;
}
else
{
return st->length;
}
}
}
}
int PrintResult(SeqTable *st, int index)
{
int i = 0;
if(index == 0)
{
printf("Not Found!\n");
return ERROR;
}
for(i = 1; i <= st->length; i++)
{
printf("%d,", st->key[i]);
}
printf("\b;\nIn %d\n", index);
return OK;
}
int main(int argc, char *argv[])
{
int index = 0;
SeqTable *st = NULL;
st = CreateSeqTable();
index = SequentialSearch(st, 52);
PrintResult(st, index);
index = SequentialSearch(st, 15);
PrintResult(st, index);
index = FibonacciSearch(st, 73);
PrintResult(st, index);
system("pause");
free(st);
return 0;
}