• 6-10 二分查找 (20 分)


    题目地址https://pintia.cn/problem-sets/15/problems/923

    就是二分查找裸题,把程序读清楚就差不多了。

    本地写的补全的裁判程序

    //-----------------------------------------------
    //code by mile
    //compiled by clion
    //no bug
    //Always get ACCEPT
    //-----------------------------------------------
    
    #include <map>
    #include <queue>
    #include <stack>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    
    #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();
    Position BinarySearch(List L, ElementType X);
    
    using namespace std;
    
    /*********************Start Here**********************************/
    
    int main()
    {
        List L;
        ElementType X;
        Position P;
    
        L = ReadInput();
        scanf("%d", &X);
        P = BinarySearch(L, X);
        printf("%d
    ", P);
    
        return 0;
    }
    
    List ReadInput()
    {
        List L;
        int n;
        scanf("%d", &n);
        for(int i = 1; i <= n; i++) scanf("%d", &L->Data[i]);
        L->Last = n;
        return L;
    }
    
    Position BinarySearch(List L, ElementType X)
    {
        int l = 1, r = L->Last, ans = 0;
    
        while(l <= r) {
            int mid = (l+r)>>1;
            if(L->Data[mid] >= X) {
                ans = mid, r = mid-1;
            } else l = mid+1;
        }
    
        if(L->Data[ans] != X) return NotFound;
        else return ans;
    }
    View Code

    提交的函数部分代码

    Position BinarySearch(List L, ElementType X)
    {
        int l = 1, r = L->Last, ans = 0;
    
        while(l <= r) {
            int mid = (l+r)>>1;
            if(L->Data[mid] >= X) {
                ans = mid, r = mid-1;
            } else l = mid+1;
        }
    
        if(L->Data[ans] != X) return NotFound;
        else return ans;
    }
    View Code
  • 相关阅读:
    TQ2440之DMA+IIS
    ST公司三轴加速度计LIS3DH应用
    TQ2440之PMW
    WinForm操作SQL Server数据库笔记
    DataRelation Learning
    SQL中join,left join,right join
    C#使用异步方式调用同步方法
    .Net Framework中的委托与事件转载
    Android site link
    【java】jdk时间差问题
  • 原文地址:https://www.cnblogs.com/mile-star/p/11448813.html
Copyright © 2020-2023  润新知