#include "stdio.h"
#include "string.h"
#include "malloc.h"
#define MAX_LIST 50
typedef struct _SqList {
int data[MAX_LIST];
int length;
}SqList;
//The key difference between Fibonacci search and binary search
//is how the anchor point is determined.
bool FibonacciSearch( SqList* L, int key, int& loc )
{
static int F[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
int low = 0;
int high = L->length - 1;
int mid;
int l = L->length;
int k = 0;
for( ; F[k] < L->length; k++ );
int *buf = L->data;
//padding with duplicate numbers if necessary
if( F[k] > MAX_LIST )
{
buf = (int*)malloc( F[k]*sizeof(buf[0]) );
memcpy( buf, L->data, L->length*sizeof(buf[0]) );
}
for( ; l < F[k]; l++ )
buf[l] = L->data[high];
l = -1;
high = F[k] - 1;
while( k > 0 && low <= high )
{
mid = low + F[k-1];
if( key < buf[mid] )
{
high = mid - 1;
k = k - 1;
}
else if( key > buf[mid] )
{
low = mid + 1;
k = k -2;
}
else
{
if( mid < L->length )
l = mid;
else
l = L->length - 1;
break;
}
}
if( buf != L->data ) free(buf);
return ( loc = l ) != -1;;
}
int main()
{
SqList d;
int intarr[] = {1,10,23,48,65,67,78,79,98,100};
memcpy( d.data, intarr, sizeof(intarr));
d.length = sizeof(intarr)/sizeof(int);
int index = 0;
for( ; index < d.length; index++ )
printf(" %d", d.data[index] );
int key = 100;
printf("\nfibonacci search %d...\n", key);
FibonacciSearch( &d, key, index );
printf("%d is at position %d\n", key, index);
printf("\n");
return 0;
}
时间: 2024-11-05 20:42:01