当前位置:   article > 正文

01-复杂度3 二分查找_typedef int position是什么意思

typedef int position是什么意思

函数接口定义:

Position BinarySearch( List L, ElementType X );

其中List结构定义如下:

  1. typedef int Position;
  2. typedef struct LNode *List;
  3. struct LNode {
  4. ElementType Data[MAXSIZE];
  5. Position Last; /* 保存线性表中最后一个元素的位置 */
  6. };

L是用户传入的一个线性表,其中ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch要查找XData中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound

裁判测试程序样例:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAXSIZE 10
  4. #define NotFound 0
  5. typedef int ElementType;
  6. typedef int Position;
  7. typedef struct LNode *List;
  8. struct LNode {
  9. ElementType Data[MAXSIZE];
  10. Position Last; /* 保存线性表中最后一个元素的位置 */
  11. };
  12. List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
  13. Position BinarySearch( List L, ElementType X );
  14. int main()
  15. {
  16. List L;
  17. ElementType X;
  18. Position P;
  19. L = ReadInput();
  20. scanf("%d", &X);
  21. P = BinarySearch( L, X );
  22. printf("%d\n", P);
  23. return 0;
  24. }
  25. /* 你的代码将被嵌在这里 */

输入样例1:

  1. 5
  2. 12 31 55 89 101
  3. 31

输出样例1:

2

输入样例2:

  1. 3
  2. 26 78 233
  3. 31

输出样例2:

0

代码: 

  1. Position BinarySearch(List L,ElementType X)
  2. {
  3. int position;
  4. int i;
  5. int end;
  6. int now;
  7. position=NotFound;
  8. i = 1;
  9. end = L->Last;
  10. now = (i + end)/2;
  11. while(i<end)
  12. {
  13. if (X==L->Data[now])
  14. {
  15. position = now;
  16. break;
  17. }
  18. else if(X>L->Data[now])
  19. {
  20. i = now + 1;
  21. now = (i + end) / 2;
  22. }
  23. else
  24. {
  25. end = now;
  26. now = (i + end) / 2;
  27. }
  28. }
  29. if (X==L->Data[now])
  30. {
  31. position = now;
  32. }
  33. return position;
  34. }

题源中国mooc

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/342795
推荐阅读
相关标签
  

闽ICP备14008679号