zoukankan      html  css  js  c++  java
  • 在数组中进行二分查找找出某数在数组中的下标

    //java coding

    
    

    import java.util.Scanner;

    /**
     * @author 
     * 2014-5-22 下午04:29:56
     * 二分查找
     */
    public class Binary_search {

    public static int device(int[] a,int c)
    {
    int begin=0;
    int end=a.length-1;
    int mid;


    while(begin<=end)
    {
    mid=(begin+end)/2;
    if(a[mid]==c)
    {
    return mid;
    }
    else if(a[mid]>c)
    {
    end=mid-1;
    }else
    {
    begin=mid+1;
    }

    }
    return -1;
    }


    public static void main(String[] args) {
    int[] a ={1,5,7,10,15,25,34,67,99};

    Scanner input = new Scanner(System.in);
    System.out.print("输入你要查找的数:");
    int c = input.nextInt();

    int index;
    //Binary_search de = new Binary_search();
    index =device(a,c);
    System.out.println(c+"这个元素"+( index==-1?"不存在":"在数组中的位置是"+index));

    /*if(( index=device(a,c))<0)
    {
    System.out.println("在数组中未找到元素"+c+"的值");
    }else
    {
    System.out.println("元素"+c+"在数组中的下标是"+index);
    }*/




    }


    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    寒假第七天
    寒假第六天
    寒假第五天
    寒假第四天
    leetcode 105 从前序与中序遍历序列构造二叉树
    leetcode 268 丢失的数字
    leetcode 141 环形链表
    判断顶点是否在三角形内部
    java 基本数据类型
    leetcode 20 有效的括号
  • 原文地址:https://www.cnblogs.com/lovelyx/p/4867161.html
Copyright © 2011-2022 走看看