• 二分查找


    算法练习

    package common;

    import java.util.Arrays;

    public class bs {

    void nbs(int n,int s[],int x)
    {
    int low=0;
    int high=n-1;
    while(low<=high)
    {
    int mid=(low+high)/2;
    if(x==s[mid])
    {
    System.out.print("p:"+mid);
    System.exit(0);
    }
    else if(x>s[mid])
    {
    low=mid+1;
    }
    else
    {
    high=mid-1;
    }

    }
    System.out.print("have no the"+x);
    System.exit(1);//非正常退出
    }

    void dbs(int s[],int low,int high,int x)
    {
    if(low>high)
    {
    System.out.print("have no the"+x);
    System.exit(1);
    }
    int mid=(low+high)/2;
    if(x==s[mid])
    {
    System.out.print("p:"+mid);
    System.exit(0);//正常退出
    }
    else if(x>s[mid])
    {
    dbs(s,mid+1,high,x);
    }
    else
    {
    dbs(s,low,mid-1,x);
    }
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    bs a=new bs();
    int s[]={1,7,9,90,888,98,78,880};
    Arrays.sort(s);

    for(int i:s)
    {System.out.println(i);}


    System.out.println("非递归二分查找:");
    a.nbs(s.length, s, 1);
    //********************************************************************
    System.out.println("递归二分查找:");
    a.dbs(s, 0, s.length-1, 90);
    //********************************************************************
    //[猪]^(* ̄(oo) ̄)^ :由于上述二分查找均为无返回值,所以结束采用exit函数,
    //因此导致nbs与dbs无法同时出结果(按顺序的话),因为exit表示jvm停止,所以注意
    }

    }

  • 相关阅读:
    组合模式
    MySQL8.0 下载安装启动(Windows10)
    OI如逆旅,我亦是行人——省选
    闲话—江湖痴情浅,信步余生。平剑红烛,青丝微绾,却话奁中。
    此时彼方
    CSP 2019游记 & 退役记
    西狂 杨过
    SDOI 2019 Round1 游记
    NOIP2018游记
    未来可期,不知所终
  • 原文地址:https://www.cnblogs.com/8335IT/p/4780753.html
Copyright © 2020-2023  润新知