zoukankan      html  css  js  c++  java
  • 二分查找

    本题要求实现二分查找算法。

    函数接口定义:

    Position BinarySearch( List L, ElementType X );
    
    L是用户传入的一个线性表,其中ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound。

    裁判测试程序样例:

    #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;
    }
    /* 你的代码将被嵌在这里 */
    

    我的代码C(gcc 6.5.0)

    Position BinarySearch( List L, ElementType X ){
        Position first,center,last;
        first = 1; //0位置不存元素
        last = L->Last;
        center = (first + last)/2;
        while(first<=last){
            if(X==L->Data[center]){
            return center;
            }else if(X>L->Data[center]){
                first = center + 1;
            }else{
                last = center - 1;
            }
            center = (first + last)/2;
        }
        return NotFound;
    }
    
  • 相关阅读:
    Pedometer_forAndroid
    linux改动登陆主机提示信息
    Cocos2d-x-Lua (2.x)脚本开发之 Lua语言基础
    共享库加载时重定位
    寻找志同道合的伙伴
    Leetcode[20]-Valid Parentheses
    storm的集群安装与配置
    CSS样式
    splash启动速度优化
    Android驱动之 Linux Input子系统之TP——A/B(Slot)协议
  • 原文地址:https://www.cnblogs.com/TangYJHappen/p/13624190.html
Copyright © 2011-2022 走看看