zoukankan      html  css  js  c++  java
  • 数组查找

    对于一维数组,通常会用到以下查找方法,来查找数组中是否存在某个元素。

    (一)逐个元素对比,找出要查找的对象

    public static int search(int[] array, int value)
    {
              for(int i = 0; i< array.length; i++)
              {
                   if(value == array[i])
                   {
                        return i;
                    }
              }
              
              return -1;
    }
    
    public static void main(Srting[] args)
    {
              int[] a = new int[]{1, 5, 3, 7 ,2 ,10,11,4};
              int value = 9;
              int index = search(a, value);
              System.out.println(index);
    }

    上述代码,查找数组a中值为9的元素的位置,由于a中没有9,所以返回-1 

    (二)使用二分法查找对象

    在使用二分法查找时,必须先为数组排序。

    折半查找法也称为二分查找法:它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如 果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右 半部继续搜索x。

    二分查找的方法可以这样写:

  • 相关阅读:
    Codeforces Round #104 (Div. 1) C. Lucky Subsequence
    UVALive 4848 Tour Belt
    ...
    HDU4609 计数问题+FFT
    hdu6129 Just Do It!
    hdu6133 Army Formations 线段树合并
    迭代FFT
    第二类Stirling数
    project euler113
    HBase 常用shell命令
  • 原文地址:https://www.cnblogs.com/vmax-tam/p/4067602.html
Copyright © 2011-2022 走看看