• 分块查找

    分块查找

    1. #include <stdio.h>
    2. #define MaxSize 100
    3. #define MaxBlk 20
    4. typedef int KeyType;
    5. typedef char ElemType[10];
    6. typedef struct
    7. {
    8. KeyType key; /*存放关键字,KeyType为关键字类型*/
    9. ElemType data; /*其他数据, ElemType为其他数据的类型*/
    10. } LineList;
    11. typedef struct
    12. {
    13. KeyType key;
    14. int low,high;
    15. } IDXType; /*索引表的类型*/
    16. int BlkSearch(LineList R[],IDXType idx[],int m,KeyType k)
    17. {
    18. int low=0,high=m-1,mid,i,j,find=0;
    19. while (low<=high && !find) /*二分查找索引表*/
    20. {
    21. mid=(low+high)/2;
    22. if (k<idx[mid].key)
    23. high=mid-1;
    24. else if (k>idx[mid].key)
    25. low=mid+1;
    26. else
    27. {
    28. high=mid-1;
    29. find=1;
    30. }
    31. }
    32. if (low<m) /*k小于索引表内最大值*/
    33. {
    34. i=idx[low].low; /*在索引表中定块起始地址*/
    35. j=idx[low].high; /*在索引表中定块终止地址*/
    36. }
    37. while (i<j && R[i].key!=k) /*在指定的块内采用顺序方法进行查找*/
    38. i++;
    39. if (i>=j)
    40. return(-1);
    41. else
    42. return(i);
    43. }
    44. void main()
    45. {
    46. KeyType a[]={9,22,12,14,35,42,44,38,48,60,58,47,78,80,77,82},k=48;
    47. LineList R[MaxSize];
    48. IDXType I[MaxBlk];
    49. int n=16,m=4,i;
    50. for (i=0;i<n;i++)
    51. R[i].key=a[i];
    52. I[0].key=22;I[0].low=0;I[0].high=3;
    53. I[1].key=44;I[1].low=4;I[1].high=7;
    54. I[2].key=60;I[2].low=8;I[2].high=11;
    55. I[3].key=82;I[3].low=12;I[3].high=15;
    56. i=BlkSearch(R,I,m,k);
    57. if (i>=0)
    58. printf("R[%d].key=%d\n",i,k);
    59. else
    60. printf("%d不在a中\n",k);
    61. }