题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1268385944106778626

参考:Binary Search in C https://www.programmingsimplified.com/c/source-code/c-program-binary-search

通过代码:

Position BinarySearch(List L, ElementType X) {
  int res;
  int startPos = 0;
  int endPos = L->Last;
  int midPos = (startPos + endPos) / 2;
  while (startPos <= endPos) {
    if (X > L->Data[midPos]) {
      startPos = midPos + 1; // NOT startPos = midPos;
      midPos = (startPos + endPos) / 2;
    } else if (X < L->Data[midPos]) {
      endPos = midPos - 1;
      midPos = (startPos + endPos) / 2;
    } else {
      res = midPos;
      break;
    }
  }
  if (startPos > endPos) {
    res = NotFound;
  }

  return res;
}

 

 

裁判程序:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;

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

List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch( List L, ElementType X );

int main()
{
    List L;
    ElementType X;
    Position P;

    L = ReadInput();
    scanf("%d", &X);
    P = BinarySearch( L, X );
    printf("%d\n", P);

    return 0;
}

/* 你的代码将被嵌在这里 */

 

 posted on 2020-08-05 15:12  邢涌芝  阅读(188)  评论(0编辑  收藏  举报