函数接口定义:

  1. 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

输入样例2:

  1. 3
  2. 26 78 233
  3. 31

输出样例2:

  1. 0

代码:

  1. Position BinarySearch(List L, ElementType X)
  2. {
  3. int end = L->Last;
  4. int first = 1;
  5. int middle = 0;
  6. while (first <= end)
  7. {
  8. middle = (end + first) / 2;
  9. if (X == L->Data[middle])
  10. return middle;
  11. if (X > L->Data[middle])
  12. {
  13. first = middle + 1;
  14. }
  15. if (X < L->Data[middle])
  16. {
  17. end = middle - 1;
  18. }
  19. }
  20. return NotFound;
  21. }
  22. List ReadInput()
  23. {
  24. int n; scanf("%d", &n);
  25. List list = (List)malloc(sizeof(struct LNode));
  26. list->Last = n;
  27. for (int i = 1; i <= n; i++)
  28. scanf("%d", &list->Data[i]);
  29. return list;
  30. }

时间复杂度

二分查找的时间复杂度是 O(logn);

二分查找针对的是有序数据。