• 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;
    }
    
    /* 你的代码将被嵌在这里 */
  • 相关阅读:
    YTU 2928: 取不重复的子串。
    YTU 2922: Shape系列-8
    YTU 2920: Shape系列-7
    STL stl_config.h
    STL defalloc.h
    STL stl_alloc.h
    STL memory.cpp
    STL stl_construct.h
    STL stl_uninitialized.h
    stl_iterator.h
  • 原文地址:https://www.cnblogs.com/simon-chou/p/13440014.html
Copyright © 2020-2023  润新知