冒牌排序及二分查找法

冒泡排序


    /**
     * 冒泡排序,,从小到大
     *
     * @param a
     * @return
     */
    public int[] sort(int a[]) {
        if (a == null) {
            throw new RuntimeException("入参错误");
        } else if (a.length == 1) {
            return a;
        }
        int count = a.length;
        for (int i = 0; i < count; i++) {
            for (int j = i + 1; j < count; j++) {
                if (a[i] > a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        return a;
    }

二分查找法:

  /**
     * 循环遍历
     *
     * @param a
     * @param target
     * @return
     */
    public int search(int a[], int target) {
        int start = 0;
        int end = a.length - 1;
        while (start <= end) {
            //中间值下标
            int index = (start + end) / 2;
            if (target == a[index]) {
                return index;
            } else if (target > a[index]) {
                start = index + 1;
            } else {
                end = index - 1;
            }

        }
        return -1;
    }

    /**
     * 递归方式
     *
     * @param a
     * @param start
     * @param end
     * @param target
     * @return
     */
    public int searchDG(int a[], int start, int end, int target) {
        int index = (start + end) / 2;
        if (a == null || start > end || a[start] > target || a[end] < target) {
            return -1;
        }

        if (target == a[index]) {
            return index;
        } else if (target > a[index]) {
            start = index + 1;
            return searchDG(a, start, end, target);
        } else {
            end = index - 1;
            return searchDG(a, start, end, target);
        }

    }

测试:

 public static void main(String[] args) {
        int a[] = {1, 5, 8, 0, 2, 4};
        BinarySearch binarySearch = new BinarySearch();
        int b[] = binarySearch.sort(a);
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
        }

        System.out.println("&&&&&&&&");
        int index = binarySearch.searchDG(b, 0, b.length - 1, 4);
        System.out.println(index);

        System.out.println("¥¥¥¥¥¥¥¥");
        int index1 = binarySearch.search(b, 4);
        System.out.println(index1);
    }

 

你可能感兴趣的:(java300集)