PAT 复杂度3 二分查找 #中国大学MOOC-陈越、何钦铭-数据结构-2020夏

题目: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
", P);

    return 0;
}

/* 你的代码将被嵌在这里 */
原文地址:https://www.cnblogs.com/simon-chou/p/13440014.html