(1)线性查找和二分搜索

线性查找算法遍历数组,直到找到查询内容,其时间复杂度为O(n)。

public static int lineatSearch(int[] list,int key)
    {
        for(int i=0;i<list.length;i++)
        {
            if(key==list[i])
               return i; 
        }
        return -1;
    }

二分搜索算法的时间复杂度为O(logn).

public static int binarySearch(int[] list,int key)
    {
        int low=0;
        int high=list.length-1;
        while(high>=low){
            int mid=(low+high)/2;
            if(key<list[mid])
                high=mid-1;
            else if(key==list[mid])
                return mid;
            else low=mid+1;
        }
        return -low-1;
    }
/** Use binary search to find the key in the list */
  public static<E extends Comparable<E>> int binarySearch(E[] list, E key) {
    int low = 0;
    int high = list.length - 1;

    while (high >= low) {
      int mid = (low + high) / 2;
      if (key.compareTo(list[mid]) < 0) {
        high = mid - 1;
      }
      else if (key.equals(list[mid])) {
        return mid;
      }
      else {
        low = mid + 1;
      }
    }

    return -low - 1; // Now high < low
  }

你可能感兴趣的:(java,二分搜索,线性查找)