java常见的几种查找算法

原文链接: https://my.oschina.net/u/2411762/blog/1576707

1、快递查找

public class BubbleSort {

    public static int QuickSearch(int[] a,int x) {  
        Boolean flag = false;
        int i;
        for (i=0;i             if (a[i] == x){
                flag = true;
                break;
            }
        }
        return a[i];
    }
    public static void main(String[] args) {
        int[] a = { 10, 20, 9, 2, 22, 49, 1 };
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        System.out.println("================");
        int searchNum = QuickSearch(a, 2);
        System.out.println(searchNum);
    }
}
 

2、二分查找

二分法查找,其要求数据序列必须是呈线性结构的,也就是说数据序列必须是排过序的才能用二分法。

public static boolean erFen2(int a[], int x) {
    boolean f = false;
    int length = a.length;
    int low = 0;
    int high = length - 1;
    int mid;
    while (low <= high) {
      mid = a[(low + high) / 2];
      if (mid < x)
        low = (low + high) / 2 + 1;
      else if (mid > x)
        high = (low + high) / 2 - 1;
      else if (mid == x) {
        f = true;
        break;
      }
    }
    return f;
}

 

转载于:https://my.oschina.net/u/2411762/blog/1576707

你可能感兴趣的:(java常见的几种查找算法)