search,searchfor

來源:互聯網
上載者:User

search,searchfor

#include "stdio.h"#include "string.h"#include "malloc.h"  #define MAX_LIST 50typedef 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.